krazymatty
krazymatty

Reputation: 125

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&

Upvotes: 7

Views: 24241

Answers (4)

rgbflawed
rgbflawed

Reputation: 2147

Here's my straightforward function for doing such a thing:

function array_urlencode($data) {
    if (is_array($data)) {
        foreach($data as $k => $v) $data_temp[urlencode($k)]=array_urlencode($v);
        return $data_temp;
    } else {
        return urlencode($data);
    }
}

Upvotes: 0

user2801665
user2801665

Reputation: 117

<!-- Encode entire array here -->

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

array_walk_recursive($input_array, 'encode');

Upvotes: -1

Anders Lien
Anders Lien

Reputation: 455

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.

Upvotes: 5

emustac
emustac

Reputation: 425

you can use serialize and the unserialize:

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

and then to decode it:

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

Upvotes: 23

Related Questions