I have an array of $ array

Array ( [gender] => 2 [cat_id] => 1 ) 

passing it as a parameter to Url::to(['catalog/', $array])

I get in the urla cracks /catalog?1%5Bgender%5D=2&1%5Bcat_id%5D=1

pliz tell me how to properly transfer the array, so that was url without unnecessary characters?

  • Something I did not find in the docks a method where you can pass a nested array ...... should be like Url::to(['catalog/', 'param1' => 'value1', 'param2' => 'value2']) .... judging by yiiframework.com/doc-2.0/guide-helper-url.html#creating-urls ........ i.e. 'param1' => 'value1', 'param2' => 'value2' is not an embedded array, this is the key of the current array's value - Alexey Shimansky
  • but you don't know how to convert an associative array to such a string like 'param1' => 'value1', are there any standard functions (I could not find it)? - Vladimir Vasilev
  • one
    you can try using the php function array_merge $url = ['catalog/']; $params = ['gender' => 2, 'cat_id' => 1]; Url::to(array_merge($url, $params)); $url = ['catalog/']; $params = ['gender' => 2, 'cat_id' => 1]; Url::to(array_merge($url, $params)); or Url::to(array_merge(['catalog/'], $params)); - Alexey Shimansky
  • worked, thanks! - Vladimir Vasilev

1 answer 1

The question is resolved in the comments, but I still write the answer, because it may be useful to someone else.

The Url::to() method can take as a first parameter either a string with a route, or an array, in which the first element will be the same string with a route, and the remaining elements will be query parameters in the key-> value format.

Those. The correct call will look like this:

 Url::to([ 'catalog', 'gender' => 2, 'cat_id' => 1 ]); 

This construct should give the url of the form /catatolg?gender=2&cat_id=1 .

In the question, call parameters look at the following way * :

 Url::to([ // не нужно в конце писать `/` 0 => 'catalog/', // параметр - массив 1 => [ 'gender' => 2, 'cat_id' => 1 ] ]); 

What does the url look like: /catalog?' . urlencode('1[gender]=2&1[cat_id]=1') /catalog?' . urlencode('1[gender]=2&1[cat_id]=1')

* considering that in PHP all arrays are actually associative, it’s just that when the keys are not explicitly indicated, then the keys are implied indices are 0, 1, 2 ...

  • Thanks for the helpful comment! - Vladimir Vasilev