2011-07-27 52 views
-3

我在php中合併了兩個數組。這裏是我的代碼我在php的array_merge中遇到問題?

$message = array_merge($message2, $message1); 
echo json_encode($message); 

在這裏我得到的數據,但在這裏打印「0」和「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"}} 
+7

可以提供一個例子 –

+1

0和1是你的數組索引!你總是可以通過改變你的數組並改變你的數組的鍵來改變它們。 – toopay

+0

iam在上面編輯我的代碼。請參閱上面的代碼 – narayana

回答

-1

你就不能的foreach它來獲得陣列的價值,然後把一個json_encode嗎?

foreach ($message as $value) { 
echo json_encode($value); 
} 
+1

這不會產生JSON數組,只是一堆JSON編碼值,而不是你想要的。你不能再用JavaScript解析這個結果。 – KilZone

+0

@KillZone,我展示了問題提問人員如何才能達到的值,他想要的值,然後他需要遍歷數組 – Orhan

+1

不,他希望JSON編碼arary而不顯示數字鍵,這可以像** hakre **所示那樣完成。如果你想要JSON encode * only *值,你必須做'json_encode(array_values($ message))',而不是循環和編碼各個值。 – KilZone

1

你描述的是json_encodeDocs正常行爲,如果陣列具有字符串鍵是不是數字,數字鍵也將被編碼。

$message1 = array('foo'); 
$message2 = array('key' => 'bar'); 

$message = array_merge($message2, $message1); 
echo json_encode($message); # {"key":"bar","0":"foo"} 

正如你可以看到那是json中的對象表示。

如果所有的鍵是數字,它們將不會被編碼的一部分:

$message1 = array('foo'); 
$message2 = array('bar'); 

$message = array_merge($message2, $message1); 
echo json_encode($message); # ["bar","foo"] 

這是JSON的數組表達。

+1

注意:如果所有鍵均爲數字*且連續並按*順序排列,則JSON結果將爲數組。試試'array(1 =>'foo',0 =>'bar')'... – deceze

+0

@deceze:['array_merge'](http://php.net/manual/en/function.array-merge。 PHP)照顧,如果輸入數組只有數字鍵。你的信息通常是一個很好的提示,但它在上面的第二個代碼示例中是* not *相關的​​,因爲數字鍵將被'array_merge'重新編號 – hakre

0

我不認爲這個結果有什麼問題。因爲你的合併陣列應該是...

(array(2)) '0' => array(username => 'foo',/* and so on */), 
      '1' => array(username => 'bar',/* and so on */)