从一个mysql表创建多维数组

时间:2012-06-03 11:26:41

标签: json multidimensional-array

我试图从一个mysql表生成嵌套的json数据,如本例所示。

var data = {
"62" : {
    "section" : "bodyImage",
    "img" : "imageurl/image62.png",
    "label" : "blue",
    "price" : "100"
},
"63" : {
    "section" : "bodyImage",
    "img" : "imageurl/image63.png",
    "label" : "red",
    "price" : "120"
}
}

62和63来自下表中的行data_id:

+-----------+------------+-------------------------+-------+---------+
| data_id   | section    | img             | label | price   | 
+-----------+------------+-------------------------+-------+----------
| 62        | bodyImage  | imagpath/image62.png    |  blue | 100     |
| 63        | bodyImage  | imagpath/image62.png    |  red  | 120     | 
+-----------+------------+-------------------------+-------+---------

+

这是带有查询的php文件:

$result = mysql_query("SELECT data_id, section, img, label, price FROM table WHERE active != 'no'");

$data = array();

while($row=@mysql_fetch_object($result)) {

$data[] = array (

    'section' => $row['sub_section'],
    'img' => $row['big_image'],
    'label' => $row['label_client_en'],
    'price' => $row['price']

);

}
echo json_encode( $data );

我无法让它发挥作用。请帮助我使用多维数组的正确语法。

1 个答案:

答案 0 :(得分:1)

你不能直接在主阵列上使用json_encode“子阵列”

您必须为while中的每个数组执行json_encode:

$data[] = json_encode(array (

'section' => $row['sub_section'],
'img' => $row['big_image'],
'label' => $row['label_client_en'],
'price' => $row['price']
));

然后你还必须像现在一样对主阵列进行编码。