I want to create a function that will process this array
$keys = array(
array(
'lev1' => 'Science',
'lev2' => 'Engineering',
'lev3' => 'Chemical Engineering'
)
);
into a tree array like
$output = array (
'Science' => array(
'Engineering' => array(
'Chemical Engineering' => array(
)
)
)
);
I am wondering if this is possible using a loop technique, something that will work even if the number of levels is not fixed (a variable) or unknown so that the output can be created dynamically. I need this for processing database data into a category tree array.
So far, this is what I have:
function build_category_tree( $keys, $output ) {
for ( $x=1; $x<=3; $x++ ) {
if ( $keys ) {
$level_key = 'lev' . $x;
$id = $keys[$level_key];
if ( ! isset( $r[$id] ) ) {
$output[$id] = array( '' );
}
}
}
return $output;
}
// Implement the function
$keys = array(
array(
'lev1' => 'Science',
'lev2' => 'Engineering',
'lev3' => 'Chemical Engineering'
)
);
foreach( $keys as $k ) {
$r = build_category_tree( $k, $r );
}
But this does not return my desired $output structure which is typical of a category tree.