I have an array of objects like below:
[
{
"TYPE": "food",
"NAME": "abc"
},
{
"TYPE": "fruit",
"NAME": "xyz"
},
{
"TYPE": "food",
"NAME": "def"
},
{
"TYPE": "food",
"NAME": "ghi"
},
]
How can I split this array of objects into multiple arrays such that the desired output looks like:
[
{
"TYPE": "food",
"ITEMS":
[
{
"TYPE": "food",
"NAME": "abc"
},
{
"TYPE": "food",
"NAME": "def"
},
{
"TYPE": "food",
"NAME": "ghi"
},
]
},
{
"TYPE": "fruit",
"ITEMS":
[
{
"TYPE": "fruit",
"NAME": "xyz"
},
]
},
]
Note that the parent object has its own identifier (TYPE)
I tried this:
$result = [];
foreach ($DT_DATA as $key => $value) {
$group = $value->TYPE;
if (!isset($result[$group])) {
$result[$group] = [];
}
$result[$group][] = $value;
}
$result = array_values($result);
But the parent group does not contain "TYPE" and also "ITEMS" array