php Yii2 - createUrl() 与参数数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31423765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Yii2 - createUrl() with array of params?
提问by Gogol
According to the Yii2 documentation, I am supposed to be building the URL like following:
根据Yii2 文档,我应该构建如下 URL:
$appUrl = Yii::$app->urlManager->createUrl([Yii::$app->controller->id . '/' . Yii::$app->controller->action->id,'p1' => 'v1','p2' => 'v2'] , null);
It outputs:
它输出:
/index.php?r=users%2Findex&p1=v1&p2=v2
/index.php?r=users%2Findex&p1=v1&p2=v2
Which is the correct output. Now, what if I have an array of params that I directly want to pass to the createUrl()
method? The following code explains my problem:
哪个是正确的输出。现在,如果我有一个我想直接传递给createUrl()
方法的参数数组怎么办?以下代码解释了我的问题:
$arrayParams = ['p1' => 'v1' , 'p2' => 'v2'];
$appUrl = Yii::$app->urlManager->createUrl([Yii::$app->controller->id . '/' . Yii::$app->controller->action->id,$arrayParams] , null);
The output in this case is:
这种情况下的输出是:
/index.php?r=users/index&1[p1]=v1&1[p2]=v2
/index.php?r=users/index&1[p1]=v1&1[p2]=v2
Whereas the output should have been:
而输出应该是:
index.php?r=users/index&p1=v1&p2=v2
index.php?r=users/index&p1=v1&p2=v2
Please note that $arrayParams
is generated by another method and I can't extract all the keys and values and pass them one by one in createUrl()
. That would be very costly IMO. How do I achieve this using Yii's api?
请注意,它$arrayParams
是由另一种方法生成的,我无法提取所有键和值并在createUrl()
. 这将是非常昂贵的 IMO。我如何使用 Yii 的 api 实现这一目标?
回答by Justinas
Use array_merge
to create required array structure.
使用array_merge
创建所需的阵列结构。
$controller = Yii::$app->controller;
$arrayParams = ['p1' => 'v1' , 'p2' => 'v2'];
$params = array_merge(["{$controller->id}/{$controller->action->id}"], $arrayParams);
Yii::$app->urlManager->createUrl($params);
回答by Vinod C
Same result you can achieve using Yii::$app->controller->route
您可以使用相同的结果Yii::$app->controller->route
$route = Yii::$app->controller->route;
$arrayParams = ['p1' => 'v1' , 'p2' => 'v2'];
$params = array_merge([$route], $arrayParams);
Yii::$app->urlManager->createUrl($params);