How do I convert an 'N' elements single dimensional array to 'N' level nested array in PHP ?
Example:
Input:
$input = array('Orange','Apple','Banana');
Expected Output:
$output = array(
'name' => 'Banana',
'sub_category' => array(
'name' => 'Apple',
'sub_category' => array(
'name' => 'Orange'
);
This is my code:
$categories = array('Orange','Apple','Banana');
$count = count($categories);
for($i=0;$i<=$count;$i++){
if(isset($categories[$i+1])){
$parent = $categories[$i+1]; // parent
$categories[$i+1]=array(
'name' => $categories[$i+1],
'sub_category' => array('name' => $categories[$i])
);
}
}
$categories = $categories[$count-1];
var_dump($categories);
My code is sloppy and I also get the following incorrect output:
$output = array(
'name' => 'Banana',
'sub_category' => array(
'name' => array(
'name' => 'Apple',
'sub_category' => array(
'name' => 'Orange'
);
);
Edit 1:
The problem/solution provided here does not seem to be answering my question.