Tuesday, August 23, 2011

n level category Array Solutions


function categoryChild($id) {
$s = “SELECT id,title FROM category WHERE  parentid=”.$id;
$r = mysql_query($s);
$children = array();
if(mysql_num_rows($r) > 0) {
# It has children, let’s get them.
while($row = mysql_fetch_array($r)) {
# Add the child to the list of children, and get its subchildren
$children[$row['id']] = categoryChild($row['id']);
}
}
return $children;
}
$array_to_save = categoryChild(’12′);
$output = ”;
$level  = ’0′;
/*
*  Call the function to print array to file
*/
$newoutput =  mulitidimentionalArrayToFile($array_to_save,$output,$level);
function mulitidimentionalArrayToFile($multiarray,&$output,$level,$key = ”,$type=’0′){
/* Check if main array or a sub array and assign “Array” to output */
if($type==’1′){
//$output .= getTabs($level);
$output .= “$key,”;
}else{
$output .= “”;
}
foreach($multiarray as $key=>$value){
/* If value is another sub array continue traversing through sub array*/
if(is_array($value)){
mulitidimentionalArrayToFile($value,$output,$level+1,$key,”1″);
}
}
return $output;
}
echo $newoutput;
echo “<br />”;
$s = $newoutput;
$s = substr($s, 0, -1);
echo $s;
result like this -> main category = 12 and below are child category
14,19,17,
15,20,18,
16,21,22

No comments:

Post a Comment