2015-07-05 72 views
0

我使用json_encode()來傳遞數據。這是我的foreach循環。格式化json_encode()

foreach ($result as $val) { 
    $data[] = array('item'=>$val["item"]); 
    $data[] = array('availability'=>$val["stocks"]);); 
} 

輸出

[ 
    { 
     "item": "Anchor Butter" 
    }, 
    { 
     "availability": "no" 
    }, 
    { 
     "item": "Kraft Chedder" 
    }, 
    { 
     "availability": "yes" 
    } 
] 

我的問題是我該怎麼辦輸出如下?

[ 
    { 
     "item": "Anchor Butter", 
     "availability": "no" 
    }, 
    { 
     "item": "Kraft Chedder", 
     "availability": "yes" 
    } 
] 

回答

4

在每次迭代中,您正在向$data數組中添加2個元素。相反,試試這個:

foreach ($result as $val){ 
    $data[] = array('item'=>$val["item"], 'availability'=>$val["stocks"])); 
} 
2
$info=array(); 
while ($row = mysql_fetch_assoc($result)) { 
    $info1= array(); 
    $info1["item"]=$row["item"]; 
    $info1["availability"]=$row["stocks"]; 
    array_push($info, $info1); 
} 
print_r($info);