I am trying to print categories in hierarchical order no matter how deep they are, I have been trying but success only for second level, what if they are 3 or four level deep. I want them to print in drop down like
Tasks
-hard task
--simple task
Notes
-hard note
--simple note
---easy note
records
$records = array(
array( 'id'=>'1', 'parent'=>'0', 'name'=>'Tasks' ),
array( 'id'=>'2', 'parent'=>'0', 'name'=>'Notes' ),
array( 'id'=>'3', 'parent'=>'1', 'name'=>'hard task' ),
array( 'id'=>'4', 'parent'=>'3', 'name'=>'simple task' ),
array( 'id'=>'5', 'parent'=>'2', 'name'=>'hard note' ),
array( 'id'=>'6', 'parent'=>'5', 'name'=>'simple note' ),
array( 'id'=>'7', 'parent'=>'6', 'name'=>'easy note' ),
);
code I am trying
function print_records($records){
foreach ($records as $rec){
echo $rec['name'];
$get_parent = $rec['parent'];
get_sub_cat($get_parent);
}
}
function get_sub_cat($get_parent){
foreach ($get_parent as $rec){
echo $rec['name'];
$get_sub = $rec['parent'];
get_sub_child_cat($get_parent);
}
}
here I am completely lost! I have seen recursion but not sure how to use in this case
What you need is called a recursion. The idea is like this:
function printLeafs($node){
echo $node->title;
$leafs = getLeafs($node);
foreach ($leafs as $leaf){
printLeafs($leaf);
}
}
Funny, there is a same qustion at the same time: PHP Print indefinite categories tree
Update:
The working solution is (to be executed from command line):
<?php
$records = array(
array( 'id'=>'1', 'parent'=>'0', 'name'=>'Tasks' ),
array( 'id'=>'2', 'parent'=>'0', 'name'=>'Notes' ),
array( 'id'=>'3', 'parent'=>'1', 'name'=>'hard task' ),
array( 'id'=>'4', 'parent'=>'3', 'name'=>'simple task' ),
array( 'id'=>'5', 'parent'=>'2', 'name'=>'hard note' ),
array( 'id'=>'6', 'parent'=>'5', 'name'=>'simple note' ),
array( 'id'=>'7', 'parent'=>'6', 'name'=>'easy note' ),
);
printLeafs($records, 0);
function printLeafs($records, $id, $depth = 0){
if ($id) {
$node = getNode($records, $id);
echo str_pad('', $depth, '-') . $node['name'] . "
";
}
$leafs = getLeafs($records, $id);
foreach ($leafs as $leaf){
printLeafs($records, $leaf['id'], $depth + 1);
}
}
function getNode($records, $id){
foreach ($records as $rec){
if ($rec['id'] == $id){
return $rec;
}
}
throw new \Exception('id "' . $id . '" not found');
}
function getLeafs($records, $parent_id){
$result = [];
foreach ($records as $rec){
if ($rec['parent'] == $parent_id){
$result[] = $rec;
}
}
return $result;
}
Also i would recommend using objects.