<?php $itemList = array( array("id" => 100,"categorypath" => "level1/powders", "product" => "Mens powder"), array("id" => 200,"categorypath" => "level1/oils/sunflower", "product" => "XYZ oil"), array("id" => 300,"categorypath" => "level1/eatable/vegetables", "product" => "carrot"), array("id" => 400,"categorypath" => "level1/oils/sunflower", "product" => "ABC oil"), array("id" => 500,"categorypath" => "level1/eatable/fruits", "product" => "mango"), array("id" => 600,"categorypath" => "level1/eatable/vegetables", "product" => "spinach"), array("id" => 700,"categorypath" => "level2/baby items/toys", "product" => "puzzle block"), array("id" => 800,"categorypath" => "level2/baby items/toys", "product" => "trucks and cars"), array("id" => 900,"categorypath" => "level2/baby items/clothes", "product" => "shirts"), array("id" => 1000,"categorypath" => "level1/powders", "product" => "Womens powder"), array("id" => 1100,"categorypath" => "level1/oils/groundnut", "product" => "GN oil"), ); // First, group products into their categories. $categoryList = []; foreach ($itemList as $item){ $categoryList[$item['categorypath']][] = [ 'id' => $item['id'] , 'path' => $item['categorypath'] , 'prodname' => $item['product'] ]; } // Now, create a tree structure out of the categories $jsonTree = ['category'=>[]]; $lookupTable = []; foreach ($categoryList as $category=>$productList){ $componentList = explode('/', $category); $path = ''; $parent = &$jsonTree; do { $component = array_shift($componentList); $path .= $component.'/'; $entry = &$lookupTable[$path]; if (!$entry){ $entry = [ 'categoryName' => $component ]; $parent['category'][] = &$entry; } $parent = &$entry; } while ($componentList); $entry['products'] = $productList; } echo json_encode($jsonTree, JSON_PRETTY_PRINT);
You have javascript disabled. You will not be able to edit any code.
This script was stopped while abusing our resources