Search code examples
phparraysmultidimensional-arrayurlencode

How to urlencode a multidimensional array?


I have searched hi and low for a solution. I have a dynamic multidimensional array I need to break up and urlencode. The number of items will change but they will always have the same keys.

$formFields = Array ( 
[0] => Array ( [form_name] => productID [form_value] => 13 ) 
[1] => Array ( [form_name] => campaign [form_value] => [email protected] ) 
[2] => Array ( [form_name] => redirect [form_value] => http://example.com ) ) 

Each array has a Form Name and a Form Value.

This is what I'm trying to get to:

$desired_results = 
productID => 13
campaign => [email protected]
redirect => http://example.com

Every time I try and split them up I end up with: form_name => productID or something like that.

I'm trying to take the results and then urlencode them:

productID=13&campaign=email&gmail.com&redirect=http://example.com&

Solution

  • This will return the values regardless of the names of the keys.

    $result = array();
    
    foreach ($formFields as $key => $value)
    {
      $tmp = array_values($value);
      $result[$tmp[0]] = $tmp[1];
    }
    print(http_build_query($result));
    

    The foreach loops through the main array, storing the subarrrays in the variable $value. The function array_values return all the values from each array as a new numeric array. The value of [form_name] will be stored in the first index, [form_value] in the second.

    The built in http_build_query function will return a urlencoded string.