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

これを試して:

$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 に答える
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 に答える