[Solved] Group array of objects into deeper parent-child structure


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;
}

0

solved Group array of objects into deeper parent-child structure