我使用PHP从json中的mysql表中检索数据,即
$table_first = 'recipe';
$query = "SELECT * FROM $table_first";
$resouter = mysql_query($query, $conn);
$set=array();
while ($link = mysql_fetch_array($resouter, MYSQL_ASSOC)){
foreach ($link as $fieldname => $fieldvalue){
$set[]= $fieldvalue;}
$query2="SELECT ingredients.ingredient_id,ingredients.ingredient_name,ingredients.ammount FROM ingredients where rec_id = ".$link['rec_id'];
$result2 = mysql_query($query2, $conn);
while ($rs = mysql_fetch_array($result2, MYSQL_ASSOC)){
foreach($rs as $fieldname =>$fieldvalue){
$set[]=$fieldvalue;
}
}
}
echo json_encode($set);
代码的结果是
["14","Spaghetti with Crab and Arugula","http:\/\/www","","2010-11-11 14:35:11","localhost\/pics\/SpaghettiWithCrabAndArugula.jpg",
"7","13 ounces spaghetti","10 kg",
"8","1 pound crabmeat","10"]
注意:成分id在图像标记之后开始。 7是成分id后跟两个字段“成分txt和数量”,然后8是与食谱id相关的另一成分id。 就像我的结果中没有({)open或(})关闭括号。
我想要做的是以正确的json格式输出它。即
[
{
"rec_id": "14",
"name":"Spaghetti with Crab and Arugula",
"overview":"http:\/\/www",
"category":"category",
"time":"2010-11-11 14:35:11",
"image":"localhost\/pics\/SpaghettiWithCrabAndArugula.jpg"
"ingredients":
{
"ingredient":
[ {"ingredient_id":"7","ingredient_name":"13ounces spaghetti","amount":"10kg" },
{ "ingredient_id": "8", "ingredient_name": "1 pound crabmeat","amount":"10kg" },
]
}]
和食谱id 15相同.......
所以怎么能得到这个.... !!任何建议
答案 0 :(得分:2)
你输出的是完全有效的json。
那么看看你如何构建$set
......看看问题了吗?
你只是将标量值推送到一个数组上,所以当你对它进行json编码时,你会得到一长串的标量,没有结构就不足为奇了。您的代码正在积极破坏您想要的结构!
我可以为你修复你的代码,但我不会这样做。你需要查看你的查询和循环,并弄清楚发生了什么。
你基本上想做这样的事情:
$result = array();
$recipes = mysql_query('....');
while($recipe = mysql_fetch_assoc($recipes)){
$result[$recipe['id']] = $recipe;
$ingredients = mysql_query('...');
while($ingredient = mysql_fetch_assoc($ingredients)){
$result[$recipe['id']] = $ingredient;
}
}
var_dump($result); //or echo json_encode($result);
看到差异?