1

我用过MySql_fetch_assoc 然后json_encode

    $type = mysql_query("SELECT type_food,category_food,name_food FROM menu ORDER BY type_food,category_food,name_food"); 
    $rows = array();
    while($t = mysql_fetch_assoc($type)) { 
          $rows[]= $t;      
    }
print json_encode($rows);

这给了我以下结果:

    {"type_food":"pizza","category_food":"Gourmet","name_food":"pepperoni"},
{"type_food":"pizza","category_food":"Gourmet","name_food":"supreme"},
{"type_food":"pizza","category_food":"Gourmet","name_food":"hawaiian"},
{"type_food":"pizza","category_food":"Gourmet","name_food":"tropical"},
{"type_food":"pizza","category_food":"traditional","name_food":"margherita"},
{"type_food":"pizza","category_food":"traditional","name_food":"vegetarian"}

但是我需要像这样制作一个多维 json 结果:

{"pizza": [
    {"Gourmet": [
                {"pepperoni"},
                {"supreme"},
                {"hawaiian"},
                {"tropical"}]},
    {"traditional": [
                {"margherita"},
                {"vegetarian"}]}
]},
{"etc": [ ... ]}

这可能使用 MySQL 关联数组吗?

4

2 回答 2

1
<?php
$str='[{"type_food":"pizza", "category_food":"Gourmet", "name_food":"pepperoni"},
{"type_food":"pizza","category_food":"Gourmet","name_food":"supreme"},
{"type_food":"pizza","category_food":"Gourmet","name_food":"hawaiian"},
{"type_food":"pizza","category_food":"Gourmet","name_food":"tropical"},
{"type_food":"pizza","category_food":"traditional","name_food":"margherita"},
{"type_food":"pizza","category_food":"traditional","name_food":"vegetarian"}]';
$rows=json_decode($str,true);
$res=array();
foreach($rows as $row)
{
  $res[$row['type_food']][$row['category_food']][]=$row['name_food'];
}
echo json_encode($res);
?>
于 2013-03-05T04:41:15.483 回答
1

试试这个:

$type = mysql_query("SELECT type_food,category_food,name_food FROM menu ORDER BY type_food,category_food,name_food"); 
$rows = array();
while($t = mysql_fetch_array($type)) { 
$rows[$t['type_food']][$t['category_food']][]=$t['name_food'];
}
print json_encode($rows);
于 2013-03-05T06:07:28.300 回答