I have a PHP array as follows
Array ( [1] => Array ( [id] => 1 [name] => Main Category [parent_id] => null ) [2] => Array ( [id] => 2 [name] => sub category [parent_id] => 1 ) [3] => Array ( [id] => 3 [name] => child category [parent_id] => 2 ) [4] => Array ( [id] => 4 [name] => Main category 1 [parent_id] => null ) [5] => Array ( [id] => 5 [name] => sub category 1 [parent_id] => 4 ) [6] => Array ( [id] => 6 [name] => child category 1 [parent_id] => 5 ) )
and I want this array to be converted as below using PHP
$categories = array( array( 'id' => 1, 'Name' => "Main Category", 'sub' => array( id => 2, 'Name' => 'Sub Category', 'sub' => array( 'id' => 3, 'Name' => 'Child category', 'sub' => 'None', ) ) ), array( 'id' => 4, 'Name' => "Main Category 1", 'sub' => array( id => 5, 'Name' => 'Sub Category 1', 'sub' => array( 'id' => 6, 'Name' => 'Child category 1', 'sub' => 'None', ) ) ) );
Actually I have a 3 level list hierarchy that looks something like this
A 1 level B 2 level under A C 2 level under A D level 3 under C E 1 level F 1 level G 2 level under F
If provided information is not enough please ask me any question in comment. So the final output for my given example will look as below
Main category sub category child
Main category 1 sub category 2 child category 3
Here is what I tried.
foreach ($categoryList as $key => $value) { if ($value->getCategoryId()!=1) { $category[$key]['id'] = $value->getCategoryId(); $category[$key]['name'] = $value->getName(); // $category[$key]['parent_id'] = $value->getParentCategoryIds(); $category[$key]['sub'] = $this->createSubCategoryArray($value->getCategoryId(), $categoryList); } } public function createSubCategoryArray($parentCatId, $categoryList) { foreach ($categoryList as $key => $category) { if($category->getCategoryId() == $parentCatId && $category->getCategoryId()!=1){ echo "string"; return array( 'id' => $category->getCategoryId(), 'name' => $category->getName(), 'sub' => $this->createSubCategoryArray($category->getCategoryId(), $categoryList) ); } } }