My input data is an array of objects. I need to restructure these objects so that an object with value = 0
becomes a "parent" object with a subarray which will collect all subsequent objects until another "parent" object is encountered.
Sample array:
$array = [
(object) ['id'=> 1, 'value' => 0],
(object) ['id'=> 2, 'value' => 10],
(object) ['id'=> 3, 'value' => 14],
(object) ['id'=> 4, 'value' => 0],
(object) ['id'=> 5, 'value' => 21],
(object) ['id'=> 6, 'value' => 44],
];
The desired result:
[
(object) [
'id' => 1,
'value' => 0,
'values' => [
(object) ['id' => 2, 'value' => 10],
(object) ['id' => 3, 'value' => 14],
],
],
(object) [
'id' => 4,
'value' => 0,
'values' => [
(object) ['id' => 5, 'value' => 21],
(object) ['id' => 6, 'value' => 44],
]
]
]
I'm struggling to make a start. Should I approach this with a foreach?
foreach ($array as $item) {
// What to do?
}