2010-12-06 55 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