We have a list of random categories which needs to arranged in a JSON output as per folowing rules - a. all parent categories should be sorted alphabetically b. each parent category should have an arry of its children sorted alphabatecally c. parent-child relationship can be multilevel
function hierarchy($data){
$arr=array();
foreach($data as $row){
$subarr=[];
if($row['parent']==null){
$subarr[$row['_id']]=$row;
$childs=findcs($row,$data);
print_r($childs);
}
array_push($arr,$subarr);
}
print_r($arr);
}
function findcs($row,$data){
$allChilds=[];
foreach($data as $item){
if($item['_id']==$item['parent']){
$child=[];
$child[$item['_id']]=$item;
array_push($allChilds,$child);
findcs(item['_id'],$data);
}
}
return $allChilds;
}
$data=[
[
"name"=> "Travel",
"parent"=> null,
"_id"=> 1,
],
[
"name"=>"Air Travel",
"parent"=> 1,
"_id"=> 1212,
],
[
"name"=> "Hotel",
"parent"=> 1,
"_id"=>212,
],
[
"name"=> "Businss Exp",
"parent"=> null,
"_id"=> 2,
],
[
"name"=> "Taxes",
"parent"=> 2,
"_id"=> 34,
],
[
"name"=> "Local Tax",
"parent"=> 34,
"_id"=> 34111,
],
[
"name"=>"Licenses",
"parent"=> 34,
"_id"=> 111232,
],
[
"name"=> "Insurance",
"parent"=> 1212,
"_id"=>113412,
],
];