2012-08-17 76 views
1

我有此類別表如何使用PHP PDO和MySQL對數組中的對象進行分組?

Category 
============ 
id name ref_id 
1  cat1 0 
2  cat2 0 
3  subCat1 1 
4  subCat2 1 
5  subCat3 2 
6  subCat4 2 

我想有一個結果是這樣的:我試圖通過解決這個

{items: [ 
    {catId: 1, subCat:[{name: subCat1}, {name:subCat2}]}, 
    {catId: 2, subCat:[{name: subCat2}, {name:subCat4}]} 
]} 

$db = new PDO('mysql:host=localhost;dbname=test;charset=UTF-8', '', ''); 

$categories = $db -> query('SELECT * FROM category'); 

$results = array('items' => array()); 

foreach($categories as $row) { 
    $subCategories = array(); 
    $results['items'][] = array('id' => $row['video_id'], 'subCat' => $subCategories); 
} 

echo json_encode($results); 

我在這種情況下,不知道如何處理subCategories。或者我做什麼來解決$類別的查詢?有什麼建議麼?謝謝。

+0

的可能重複[如何在一個陣列I組陣列, PHP和編碼到JSON?](http://stackoverflow.com/questions/11997109/how-can-i-group-arrays-in-an-array-in-php-and-encode-to-json) – KingCrunch 2012-08-17 08:16:06

回答

2

獲取根類別,您需要將where ref_id=0添加到您的查詢中。然後在您的foreach循環中,您需要再次查詢以獲取當前行的子類別(在第二個查詢中使用"where ref_id=".$row['id'])。您使用另一個foreach循環編譯$subCategories陣列。 O,我用您的代碼將'id' => $row['video_id']替換爲'catId' => $row['id']以獲得您需要的結果。

如下:

<?php 
$db = new PDO('mysql:host=localhost;dbname=test', '', ''); 

$categories = $db->query('SELECT * FROM category where ref_id=0'); 

$results = array('items' => array()); 

foreach($categories as $row) { 
    $subCategories = array(); 

    $sCategories = $db->query('SELECT * FROM category where ref_id='.$row['id']); 
    foreach($sCategories as $subCat){ 
    $subCategories[] = array('name'=>$subCat['name']); 
    } 

    $results['items'][] = array('catId' => $row['id'], 'subCat' => $subCategories); 
} 

echo json_encode($results); 

我已經重新在我的身邊你的數據庫,當我跑,我得到

{"items":[ 
    {"catId":"1","subCat":[{"name":"subcat1"},{"name":"subcat2"}]}, 
    {"catId":"2","subCat":[{"name":"subcat3"},{"name":"subcat4"}]} 
]} 
+0

+ 1用於重新創建數據庫以測試:) – epoch 2012-08-22 12:39:40

相關問題