How to create a tree of category subcatagory in php -
i trying create tree ordered select box array of category, subcategory data. array
array ( [0] => array ( [id] => 6 [cata_key] => 32e9c75e38d2a1d77b2b49b2 [cata_name] => road [app_key] => b80e0935b348da61b2a807ff [parentid] => 0 ) [1] => array ( [id] => 7 [cata_key] => 56bae4297efcbf796b230a99 [cata_name] => river [app_key] => b80e0935b348da61b2a807ff [parentid] => 0 ) [2] => array ( [id] => 8 [cata_key] => 1c748603f36105b921b54165 [cata_name] => air [app_key] => b80e0935b348da61b2a807ff [parentid] => 0 ) [3] => array ( [id] => 9 [cata_key] => 780c3eb53264d5c33a26d49f [cata_name] => cars [app_key] => b80e0935b348da61b2a807ff [parentid] => 6 ) [4] => array ( [id] => 10 [cata_key] => 111cd06b1575457f665d460e [cata_name] => hyundai [app_key] => b80e0935b348da61b2a807ff [parentid] => 9 ) [5] => array ( [id] => 11 [cata_key] => 26ca0e1622c11ed2628eaadf [cata_name] => maruthi [app_key] => b80e0935b348da61b2a807ff [parentid] => 9 ) [6] => array ( [id] => 12 [cata_key] => 7fc72e49fe67d0b777648f54 [cata_name] => boat [app_key] => b80e0935b348da61b2a807ff [parentid] => 7 ) [7] => array ( [id] => 13 [cata_key] => b6125c73f6d7c153f45e133e [cata_name] => ship [app_key] => b80e0935b348da61b2a807ff [parentid] => 7 ) [8] => array ( [id] => 14 [cata_key] => 38c749056a9f583e284e509b [cata_name] => 2 seater [app_key] => b80e0935b348da61b2a807ff [parentid] => 12 ) [9] => array ( [id] => 15 [cata_key] => 6ebfcad4d4e05e84d333b7e5 [cata_name] => 10 seater [app_key] => b80e0935b348da61b2a807ff [parentid] => 12 ) [10] => array ( [id] => 16 [cata_key] => 49973084640af71ad61e634b [cata_name] => bikes [app_key] => b80e0935b348da61b2a807ff [parentid] => 6 ) )
in parentid points parent category. resultant array should in order of
road ->cars -> hyndai -> maruthi -> bikes river -> boats -> 2 seater -> 10 seater -> ship air
<?php $categories = array( array('id' => 1, 'parent' => 0, 'cata_name' => 'road'), array('id' => 2, 'parent' => 1, 'name' => 'cars'), array('id' => 3, 'parent' =>2, 'name' => 'maruthi'), array('id' => 4, 'parent' => 2, 'name' => 'hyundai') ); function categoriestotree(&$categories) { $map = array( 0 => array('subcategories' => array()) ); foreach ($categories &$category) { $category['subcategories'] = array(); $map[$category['id']] = &$category; } foreach ($categories &$category) { $map[$category['parent']]['subcategories'][] = &$category; } return $map[0]['subcategories']; } $tree = categoriestotree($categories); echo "=== tree ===\n"; echo "<pre>"; print_r ($tree); ?>
Comments
Post a Comment