I have an array that returns the following:
$products = [
'product' => [
[
"product_parent" => "Parent Name 1",
"product_name" => "Product 1",
],
[
"product_parent" => "Parent Name 1",
"product_name" => "Product 2",
],
[
"product_parent" => "Parent Name 2",
"product_name" => "Product 1",
],
[
"product_parent" => "Parent Name 3",
"product_name" => "Product 1",
]
]
];
I need to return a new array that is structured like this that is an (indexed) array of (associative) arrays
'product' => [
0 => [
'product_name' => 'Parent Name 1'
'product_info' => [
0 => [
"product_name" => "Product 1",
],
1 => [
"product_name" => "Product 2",
]
]
],
1 => [
'product_name' => 'Parent Name 2'
'product_info' => [
0 => [
"product_name" => "Product 1",
],
1 => [
"product_name" => "Product 2",
]
]
]
]
I've tried various foreach loops but I can't figure out a way to get the index set properly like the desired output I have above.
What I've Tried:
I also was originally working on this method, which is more efficient as it does less queries and improves performance. Hopefully this helps someone in the future.
$variables = [];
foreach($query_results as $key => $group) {
$sub_groups = $this->db->select('*')
->from('products')
->where('parent_id', $group['id'])
->get();
$variables[0]['product'][$key]['product_group'] = $group['product_name'];
$variables[0]['product'][$key]['product_info'] = array_values($sub_groups->result_array());
}
This will return the type of array structure I desired above, but with better performance.