Vicheanak
Vicheanak

Reputation: 6684

How to group Objects in an Array using PHP PDO and MySQL?

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.

Upvotes: 1

Views: 1346

Answers (1)

pho
pho

Reputation: 530

Getting the root categories, you need the add where ref_id=0 to your query. And then in your foreach loop, 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 $subCategories array using another foreach loop. O, and I replaced 'id' => $row['video_id'] from your code, to 'catId' => $row['id'] to get the result you require.

As follows:

<?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);

I have recreated your database on my side, and when I run this, I get

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

Upvotes: 2

Related Questions