我有此類別表如何使用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。或者我做什麼來解決$類別的查詢?有什麼建議麼?謝謝。
的可能重複[如何在一個陣列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