2015-05-20 95 views
0

我想獲得類似於將數據添加到數組上的內容,但是當我使用此方法時,會在json元素中創建兩個節點。我只想要一個包含所有實體的節點,還可以命名節點,即屬性。Json數組添加到php數組

$json = array(); 

while($row = mysql_fetch_assoc($sth)) { 
    $json['name'] = $row['name']; 
    $json['id'] = $row['id']; 
    $data[] = $json; 
} 

$custom = array('name'=>'foo', 'id' => 'bar'); 
$data[] = $custom; 
+0

你可以添加你得到什麼,你期待? – Naruto

+0

像這樣'{name:[「foo」,「bar」],id:[1,2]}'??? – Girish

回答

0

試試這個代碼array_push是更好的選擇,在這裏,

<?php 
    $json = array(); 

    while($row = mysql_fetch_assoc($sth)) { 
     $temp = array(); 
     $temp = array('name' => $row['name'], 'id' => $row['id']); 
     array_push($json, $temp); 
    } 

    $custom = array('name'=>'foo', 'id' => 'bar'); 
    array_push($json,$custom); 

    ?> 
+0

爲什麼'array_push()'更好?這只是一個額外的函數調用。與$ json [] ='相同。你爲什麼要初始化'$ temp'兩次? – TiMESPLiNTER

+0

這很容易理解$ json ['name'] = $ row ['name']; $ json ['id'] = $ row ['id']; $ data [] = $ json; OR $ temp = array(); $ temp = array('name'=> $ row ['name'],'id'=> $ row ['id']); array_push($ json,$ temp); –

+0

key由array_push自動維護{$ custom = array('name'=>'foo','id'=>'bar'); array_push($ json,$ custom); } –