I am developing a CodeIgniter application and I need to restructure a query result coming from a model method so produce a multi-level, hierarchial associative array.
My model provides the following payload:
$array = [
['id' => 1, 'category' => 'Pizza', 'product' => 'Large Pizza', 'complement_type' => 'Bread', 'option' => 'Brown bread'],
['id' => 2, 'category' => 'Pizza', 'product' => 'Small Pizza', 'complement_type' => 'Bread', 'option' => 'White bread'],
['id' => 3, 'category' => 'Pizza', 'product' => 'Small Pizza', 'complement_type' => 'Ingredients', 'option' => 'Olives'],
['id' => 4, 'category' => 'Salads', 'product' => 'Green Salad', 'complement_type' => 'Extras', 'option' => 'Bacon'],
['id' => 5, 'category' => 'Salads', 'product' => 'Cesars Salad', 'complement_type' => 'Extras', 'option' => 'Lettuce'],
];
I need to nest the data in a particular order:
category -> product -> complement_type = option
My desired structure:
array (
'Pizza' =>
array (
'Large Pizza' =>
array (
'Bread' => 'Brown bread',
),
'Small Pizza' =>
array (
'Bread' => 'White bread',
'Ingredients' => 'Olives',
),
),
'Salads' =>
array (
'Green Salad' =>
array (
'Extras' => 'Bacon',
),
'Cesars Salad' =>
array (
'Extras' => 'Lettuce',
),
),
)
I think I have to loop it with a for()
loop, maybe add a while()
loop to get the changes in the categories, but I just can't seem to find the way to do it.