I am regular user at stackoverflow. Post lunch, while seeing the question list for php I came to a question where user wanted to

List N Depth Categories Depth Wise

The Problem was like

table category_path it is in parent child relationship and its look like this


 

User wanted to display result like as below:

The question was interesting. Initially I though that it is so easy can be easily done with self joining of table on id to parent_category_id. But I was wrong. It was not so easy as considered.

After spending whole evening I got the solution is as below:

I have considered that user can easily fetch table values into array and then perform as given:

<?php

function findValue($key,$src){

return $src[$key];
}

function inPatentList($val, $patent_list){

return (in_array($val, $patent_list)) ? true : false;
}

function findFullTraverse($id, $src,&$str){
if(0 != ($value = findValue($id, $src))){
if($str==”){
$str .= $value;
}else{
$str .= ‘_’.$value;
}
findFullTraverse($value,$src,$str);
}
}
$id_parent = array(
‘1’ => ‘0’,
‘2’ => ‘1’,
‘3’ => ‘2’,
‘4’ => ‘1’,
‘5’ => ‘3’,
‘6’ => ‘2’,
);
$parent = array_values($id_parent);
$ids = array_keys($id_parent);

$depth = array();
$keys_for_value = array();
$id_parent = array_reverse($id_parent, true);
foreach($id_parent as $key => $val){

$depth[] = $key.’_’.$key.’_0′;
if(inPatentList($key, $parent)){
$keys_for_value = array_keys($id_parent, $key);
$depth_found[$key] = $keys_for_value;
foreach ($depth_found[$key] as $value){
$str = ”;
findFullTraverse($value, $id_parent,$str);
//echo $value.’=>’.$str.'<br/>’;
$traverse_array = explode(‘_’, $str);
for($i=0;$i<sizeof($traverse_array);$i++){
$has_depth = $i + 1;
$depth[]=$traverse_array[$i].’_’.$value.’_’.$has_depth;
}
}
}
}

sort($depth);
echo ‘<pre>’;
print_r($depth);
echo ‘<pre>’;

?>

 Its really gives nice feeling when solving complex problem.

Advertisements