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?
}
not really sure the purpose of this exercise but this gets your desired result with the given data
$objects = [
(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],
];
$data = [];
foreach($objects as $object) {
if ($object->value === 0) {
$data[] = $object;
continue;
}
$current = end($data);
if (!isset($current->values)) {
$current->values = [];
}
$current->values[] = $object;
}