简体   繁体   中英

Yii2 - createUrl() with array of params?

According to the Yii2 documentation , I am supposed to be building the URL like following:

$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

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:

$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

Whereas the output should have been:

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?

Use array_merge to create required array structure.

$controller = Yii::$app->controller;
$arrayParams = ['p1' => 'v1' , 'p2' => 'v2'];

$params = array_merge(["{$controller->id}/{$controller->action->id}"], $arrayParams);

Yii::$app->urlManager->createUrl($params);

Same result you can achieve using Yii::$app->controller->route

$route = Yii::$app->controller->route;
$arrayParams = ['p1' => 'v1' , 'p2' => 'v2'];
$params = array_merge([$route], $arrayParams);
Yii::$app->urlManager->createUrl($params);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM