nested json using php and mysql

here is the solution for you, see the code below and also check Live Demo for this…

<?php 
$data=array();

$all  = array(
            array('id'=>1,'ParentID'=>'0','type'=>'Men'),
            array('id'=>2,'ParentID'=>'0','type'=>'Women'),
            array('id'=>3,'ParentID'=>'0','type'=>'Kids'),
            array('id'=>4,'ParentID'=>'1','type'=>'Shirt'),
            array('id'=>5,'ParentID'=>'2','type'=>'Top'),
            array('id'=>6,'ParentID'=>'3','type'=>'Shoes'),
            array('id'=>7,'ParentID'=>'4','type'=>'p1'),
            array('id'=>8,'ParentID'=>'5','type'=>'p1'),
            array('id'=>9,'ParentID'=>'6','type'=>'p1'),
            array('id'=>10,'ParentID'=>'4','type'=>'p2'),
            array('id'=>11,'ParentID'=>'5','type'=>'p2'),
            array('id'=>12,'ParentID'=>'6','type'=>'p2')
        );

foreach($all as $key => $val)
{
    if($val['ParentID']==0)
    {
        $data[$key]=$val;

        foreach($all as $k => $v)
        { 
            if($val['id'] == $v['ParentID']){
                $data[$key]['subBranches'][$key]= $v;
                foreach($all as $a => $s)
                { 
                    if($v['id'] == $s['ParentID']){
                        $data[$key]['subBranches'][$key]['sub_subBranches'][]= $s;
                    }
                }
            }
        }
    }
}
echo json_encode($data);
?>

Your json array is like :

[
  {
    "id":1,
    "ParentID":"0",
    "type":"Men",
    "subBranches":[
      {
        "id":4,
        "ParentID":"1",
        "type":"Shirt",
        "sub_subBranches":[
          {
            "id":7,
            "ParentID":"4",
            "type":"p1"
          },
          {
            "id":10,
            "ParentID":"4",
            "type":"p2"
          }
        ]
      }
    ]
  },
  {
    "id":2,
    "ParentID":"0",
    "type":"Women",
    "subBranches":{
      "1":{
        "id":5,
        "ParentID":"2",
        "type":"Top",
        "sub_subBranches":[
          {
            "id":8,
            "ParentID":"5",
            "type":"p1"
          },
          {
            "id":11,
            "ParentID":"5",
            "type":"p2"
          }
        ]
      }
    }
  },
  {
    "id":3,
    "ParentID":"0",
    "type":"Kids",
    "subBranches":{
      "2":{
        "id":6,
        "ParentID":"3",
        "type":"Shoes",
        "sub_subBranches":[
          {
            "id":9,
            "ParentID":"6",
            "type":"p1"
          },
          {
            "id":12,
            "ParentID":"6",
            "type":"p2"
          }
        ]
      }
    }
  }
]

Browse More Popular Posts

Leave a Comment