|Array to string conversion|
| 7:55 am on Feb 11, 2009 (gmt 0)|
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] = 'item 1';
$arr[Profile][item] = 'item 2';
$arr[Profile][item] = '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]=item 1&data[Profile][item]=item 2&data[Profile][item]=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!
| 8:33 am on Feb 11, 2009 (gmt 0)|
Try the following code but I haven't tested it
function a2s ($name, $var)
$s = "$name=$var";
$s = "";
foreach($var as $key => $value)
if ($s != "")
$s .= "&";
$s .= a2s("$name[$key]", $value);
And call with
$str = a2s("data", $arr);
| 10:10 am on Feb 11, 2009 (gmt 0)|
Thanks for the pointer, adb64. The code actually didn't work, but I managed to find another way of doing it :) I've posted the code below:
$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);
Might not be the most efficient of ways, but it works for what I need it for :)
Thanks for the help anyway.
| 2:05 pm on Feb 11, 2009 (gmt 0)|
What do you need it for? POST data, as you first stated?
|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));
I added the 'data' index for the entire array as that is what you seem to want.