开发者

I am getting problem in array_merge in php? [closed]

开发者 https://www.devze.com 2023-03-23 11:12 出处:网络
It's difficult to tell what is being asked here. This开发者_如何学C question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form.
It's difficult to tell what is being asked here. This开发者_如何学C question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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_encodeDocs, 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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消