2012-06-03 51 views
0

我想从一个mysql表中生成像这个例子中的嵌套json数据。从一个mysql表创建多维数组

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([email protected]_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

不能json_encode直接在主阵列

您必须在您同时每个阵列做json_encode的“子阵列”:

$data[] = json_encode(array (

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

然后,还必须在主阵列编码为你已经做。