Forum Moderators: coopster
Okay, I've been struggling with this issue quite a bit. Let's say I have an array that I need to convert to a string, in order to post it off to some URL.
I know this is going to need to be accomplished using recursion, but for the life of me I don't know how to go about it :(
Here's an example of the input:
$arr[Profile][name] = 'my name';
$arr[Profile][surname] = 'surname';
$arr[Profile][item][0] = 'item 1';
$arr[Profile][item][1] = 'item 2';
$arr[Profile][item][2] = 'item 3';
$arr[foo][bar][foo1][bar2] = 'blerg';
And this is what it needs to look like (in order to do a normal POST, and it needs to be as a string):
data[Profile][name]=my name&data[Profile][surname]=surname&data[Profile][item][0]=item 1&data[Profile][item][1]=item 2&data[Profile][item][2]=item 3&data[foo][bar][foo1][bar2]=blerg
I hope this makes sense, and that there is someone that can help me. I'm at my wits' end as to how to accomplish this!
Cheers,
Geoff
function data($data)
{
$data['Test']['test2']['test3'] = array(1,2,3,4,5,6,7,8,9,0);
$post = http_build_query($data, '', '¦<&>¦');
$post = str_replace(array('%5B', '%5D'), array('[', ']'), $post);
$post = preg_replace(array('#(\¦<&>\¦)([^[]*)#i', '#^([^[]*)#i'), array('&data[$2]', 'data[$1]'), $post);
return $post;
}
Might not be the most efficient of ways, but it works for what I need it for :)
Thanks for the help anyway.
in order to post it off to some URL
If so, it is quite simple, just use the PHP built in function http_build_query [php.net]:
$post = http_build_query(array('data' => $arr));