I have this category table
Category
============
id name ref_id
1 cat1 0
2 cat2 0
3 subCat1 1
4 subCat2 1
5 subCat3 2
6 subCat4 2
I would like to have a result that look like this:
{items: [
{catId: 1, subCat:[{name: subCat1}, {name:subCat2}]},
{catId: 2, subCat:[{name: subCat2}, {name:subCat4}]}
]}
I’ve tried to approach this by:
$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);
I have no clue of what to do with subCategories in this case. Or Anything I do to fix the query of $categories? Any suggestions? thanks.
Getting the root categories, you need the add
where ref_id=0to your query. And then in yourforeachloop, you need to query again to get the current row’s sub-categories (using"where ref_id=".$row['id']in the second query). You compile the$subCategoriesarray using anotherforeachloop. O, and I replaced'id' => $row['video_id']from your code, to'catId' => $row['id']to get the result you require.As follows:
I have recreated your database on my side, and when I run this, I get