2013-11-22 76 views
0

我需要能夠按類別名稱組織我的JSON。我通過Category ID(項目)和Key(類別)將兩個錶鏈接在一起。我希望能夠將所有帶有類別ID標記的項目組織在類別表的類別名稱下。這是我到目前爲止的代碼:PHP MySQL JSON按數據組織

$query = "SELECT * FROM items,category WHERE items.category_id = category.key"; 
$result = mysql_query($query,$link) or die('Errant query: '.$query); 
while($row = mysql_fetch_array($result)) 

extract($row); 
    $channel['items'][] = array(
      'title' => $title, 
    'category_id' => $category_id, 
    'category_name' => $category_name, 
    'category_key' => $key, 
    ); 
} 
    $channels = array($channel); 
    $json = json_encode($channel); 
    header('Content-type: application/json'); 
    echo $json; 
} 

它輸出JSON是這樣的:

{ 
"items": [ 
    { 
     "title": "putting in title", 
     "category_id": "7", 
     "category_name": "Stuff 1", 
     "category_key": "7" 
    }, 
    { 
     "title": "another title", 
     "category_id": "7", 
     "category_name": "Stuff 1", 
     "category_key": "7" 
    }, 

但我需要的JSON通過類別名稱進行組織,就像這樣:

{ 
"Stuff 1": [ 
    { 
     "title": "putting in title", 
     "category_id": "7", 
     "category_name": "Stuff 1", 
     "category_key": "7" 
    }, 
    { 
     "title": "another title", 
     "category_id": "7", 
     "category_name": "Stuff 1", 
     "category_key": "7" 
    }, 
"Stuff 2": [ 
    { 
     "title": "putting in title", 
     "category_id": "7", 
     "category_name": "Stuff 2", 
     "category_key": "7" 
    }, 
    { 
     "title": "another title", 
     "category_id": "7", 
     "category_name": "Stuff 2", 
     "category_key": "7" 
    }, 

任何幫助完成這一點將不勝感激!

回答

1

試試這個:

$channel[$category_name][] = array(
     'title' => $title, 
'category_id' => $category_id, 
'category_name' => $category_name, 
'category_key' => $key, 
); 
+0

OMG!這太容易了!我很尷尬。謝謝Lauri。如果我需要將所有內容都放入項目數組中,該怎麼辦?我該怎麼辦? – mreynol

+0

你的意思是'$ channel ['items'] [$ category_name]'? –

+0

完美。非常感謝Lauri! – mreynol