简体   繁体   English

在嵌套多维数组中使用 array_column() 访问动态索引和值

[英]Using array_column() in nested multi dimensional array to access dynamic indexes and values

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但是从这里我只能取“0”个索引值,因为这是动态数组我怎么能更正我的函数来访问所有索引的 quntity 键

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() .获取line_items数据,然后使用array_merge()和 splat 运算符展平该索引有效负载,然后您可以通过再次调用array_column()来访问quantity列。

Code: ( Demo )代码:(演示

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM