简体   繁体   中英

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@gmail.com ) 
[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@gmail.com
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&

you can use serialize and the unserialize:

$str = urlencode(serialize($formFields));

and then to decode it:

$formFields = unserialize(urldecode($str));

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.

custom function for urlencode array keys and values.

function urlencode_array($array){
    $out_array = array();
    foreach($array as $key => $value){
    $out_array[urlencode($key)] = urlencode($value);
    }
return $out_array;
}
<!-- Encode entire array here -->

function encode(&$item, $key) {
$item = rawurlencode($item);
}

array_walk_recursive($input_array, 'encode');

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