1

我有两个 MySQL 表,一个用于水果,一个用于蔬菜,我想查询这些表的内容并在一个大型 JSON 字典中返回两组结果,以 Fruits 为键以返回水果数组,以蔬菜为键以返回蔬菜大批。它目前不起作用(返回 null)。

这是我当前的代码:

//query each table for every object
$fruitResult = mysql_query("SELECT * FROM Fruits");
$vegResult = mysql_query("SELECT * FROM Vegetables");

//set up an array for each kind of object
$fruits = array();
$vegetables = array();

while ($fruitRow = mysql_fetch_assoc($fruitResult)) {
    //add each result from Fruit table to array
    $fruits[] = $fruitRow;
}
while ($vegRow = mysql_fetch_assoc($vegResult)) {
    //add each result from Veggie table to array
    $vegetables[] = $vegRow;
}

//create dictionary
$dictionary = array("Fruit"=>$fruits,"Vegetables"=>$vegetables);

echo json_encode($dictionary);

我可以把这些东西分开,然后

echo json_encode($fruits);
echo json_encode($vegetables);

但是随后返回了两个单独的数组。任何人都可以解释一下吗?
我希望我的回复看起来像这样:

[{"Fruit":
    [{"id":"0","name":"apple","color":"red"},
    {"id":"1","name":"strawberry","color":"red"},
    {"id":"2","name":"grape","color":"purple"}],
{"Vegetables":
    [{"id":"0","name":"pea","color":"green"},
    {"id":"1","name":"asparagus","color":"green"},
    {"id":"2","name":"corn","color":"yellow"}]
}]
4

0 回答 0