First let me show you an image of the situation
As you can see I have an array of objects with value of 0 and value of a random int. I want to have an array that sorts out the random value objects and puts them into a new array and adds them to the 0 array. And when the arrays sees that the value is 0 again, it will create a new array. Hopefully someone understands what I mean haha.. I find it hard to explain but hopefully the image says enough.
Should I approach this with a foreach or not?
foreach ($array as $item) {
// What to do?
}
CodePudding user response:
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;
}