phparraysmultidimensional-arrayarray-column

Populate a flat array of values from a column within a column of a 4-level array


I have this nested multidimensional array for orders

[
    [
        'created_at' => 1991,
        'updated_at' => 1992,
        'customer_name' => 'john doe',
        'line_items' => [
            [
                'name' => 'Hello world poduct',
                'price' => 800.00,
                'id' => 123,
                'quantity' => 2
            ],
            [
                'name' => 'Hello world product 2',
                'price' => 100.00,
                'id' => 456,
                'quantity' => 1
            ]
        ]
    ],
    [
        'created_at' => 1992,
        'updated_at' => 1993,
        'customer_name' => 'Guido van Rossum',
        'line_items' => [
            [
                'name' => 'Hello world product',
                'price' => 800.00,
                'id' => 123,
                'quantity' => 2    
            ],
            [
                'name' => 'Hello world poduct 2',
                'price' => 100.00,
                'id' => 456,
                'quantity' => 3
            ],
            [
                'name' => 'Hello world poduct 3',
                'price' => 400.00,
                'id' => 116,
                'quantity' => 5
            ]
        ]
    ]
]

from this array I need to take the all the quantity values in to one array

This is what I've tried so far...

$newArr_items = array_column( 
    array_column(
        array_column(
            $result_3['orders'],
            'line_items'
        ),
        '0'
    ),
    'quantity'
);

but from this, I can take the "0"th index values only. Considering this is dynamic array, how can I correct my function to access the quantity key of all of the indexed subarrays?


Solution

  • Grab the line_items data, then flatten that indexed payload with array_merge() and the splat operator, then you can access the quantity column with another call of array_column().

    Code: (Demo)

    var_export(
        array_column(
            array_merge(
                ...array_column($array, 'line_items')
            ),
            'quantity'
        )
    );
    

    Variations with the same result:

    Demo

    $result = [];
    foreach ($array as ['line_items' => $items]) {
        array_push($result, ...array_column($items, 'quantity'));
    }
    var_export($result);
    

    Demo

    $result = [];
    foreach ($array as ['line_items' => $items]) {
        foreach ($items as ['quantity' => $result[]]);
    }
    var_export($result);
    

    p.s. Using array_walk_recursive() is vulnerable to unintended results if the sought deep values' key can also be found in a non-whitelisted parent column.