2010-12-06 57 views
0

我使用PHP即如何提取数据JSON格式

$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);

检索从在JSON MySQL表数据的代码的结果是

["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,后面跟着两个字段“ingredients txt and amount”,然后8是与recipe id相关的另一个成分id。 就像我的结果中没有({)打开或(})右括号。

我想要做的是以正确的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等.......

所以如何能得到这个....!任何建议

回答

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); 

见有什么不同?

+0

干草timedev你的代码只是输出的最后一个配方,即{“”:{“·REC_ID”:“23”,“名”:“这是一个类别”,“概述测试秘方”:“类别概述”,“类别“:”4“,”time“:”2002-12-10 13:30:39“,”image“:”http:\/\/www.localhost \/cafe \/pics \/logout(1)。 gif“}} – hunter 2010-12-06 06:24:07