I am getting problem in array_merge in php? [closed]
I merge two arrays in php. Here is my code
$message = array_merge($message2, $message1);
echo json_encode($message);
here I get the data but here print "0" and "1"
{"username":"ji5vajng","gender":"MALE","profilepic":"http:\/\/li336-153.members.linode.com\/services\/uploads\/users\/thumbs\/000000000000000Sunset.jpg","status":"1","nickname":"laddu","0":{"username":"i3vnbtcz","gender":"MALE","profilepic":"http:\/\/li336-153.members.linode.com\/services\/uploads\/users\/thumbs\/7BB46853-D79D-5E17-807F-FD0666AF21BBi3vnbtcz-2011-06-13 11:04:26 +0000.png","status":"1","nickname":"Cool"},"1":{"username":"oq5mjbvb","gender":"male","profilepic":"http:\/\/li336-153.members.linode.com\/services\/uploads\/users\/thumbs\/7BB46853-D79D-5E17-807F-FD0666AF21BBoq5mjbvb-2011-06-13 05:45:57 +0000.png","status":"1","nickname":""},"2":{"username":"ejzxm2oz","gender":"MALE","profilepic":"http:\/\/li336-153.members.linode.com\/services\/uploads\/users\/thumbs\/A0000015BAB1CAreceived_0.jpg","status":"1","nickname":"laddu"}}
What you describe is the normal behaviour of json_encode
Docs, if the arrays have string keys that are not numeric, the numeric keys will be encoded as well.
$message1 = array('foo');
$message2 = array('key' => 'bar');
$message = array_merge($message2, $message1);
echo json_encode($message); # {"key":"bar","0":"foo"}
As you can see that's the object representation in json.
If all keys are numeric, they won't be part of the encoding:
$message1 = array('foo');
$message2 = array('bar');
$message = array_merge($message2, $message1);
echo json_encode($message); # ["bar","foo"]
This is the array representation in json.
I dont think theres something wrong with that result. Because your merged array should be...
(array(2)) '0' => array(username => 'foo',/* and so on */),
'1' => array(username => 'bar',/* and so on */)
Can't you just foreach it to get the value of the arrays and then put a json_encode on it?
foreach ($message as $value) {
echo json_encode($value);
}
精彩评论