vincent15000's avatar

Array handling to retrieve the values in level 2

Hello,

I have this array.

$test = [
    [
        'id' => 2,
        'results' => [
            'average' => 3.5,
            'note' => 1.5,
        ]
    ],
    [
        'id' => 3,
        'results' => [
            [
                'average' => 4.5,
                'note' => 2.5,
            ],
            [
                'average' => 5.5,
                'note' => 3.5,
            ]
        ]
    ]
];

I'd like to retrieve only the average values and format them as a collection of objects.

It works fine loops, but I wonder if there is another way to do with the array helpers.

I think that the first step is to extract the average values, I have tried with Arr::pluck($test, 'results.average'), but it doesn't work, it only retrieves the first value.

Any idea to do that ?

Thanks for your advice.

V

0 likes
4 replies
vincent15000's avatar

@jlrdw Oh thank you ... well ... that's not so different compared to what I have done with loops.

I just wanted to try to do it with some array helpers offered by Laravel in order to avoid two levels loops.

The idea is perhaps to write my own helper.

jlrdw's avatar

@vincent15000 before deciding how to handle this, I suggest reviewing the various array techniques that already exist in the PHP manual.

You could flatten a level and view as needed.

1 like
vincent15000's avatar

@jlrdw Thank you very much.

I have tested this and it works fine.

$flattened_array = [];
array_walk_recursive($test, function($a, $key) use (&$flattened_array) {
    if ($key == 'average') {
        $flattened_array[] = (object) ['average' => $a];
    }
});
dd(collect($flattened_array));

Please or to participate in this conversation.