Home > Blockchain >  Using array_column() in nested multi dimensional array to access dynamic indexes and values
Using array_column() in nested multi dimensional array to access dynamic indexes and values

Time:12-16

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 only take "0" th index values only, since this is dynamic array how can I correct my function to access quntity key of all the indexes

CodePudding user response:

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'
    )
);
  • Related