Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a column from a multidimensional with deep key

I have an array which is multidimensional. I have to pull a specific key's value, but it is deep in the array. I'm trying to find the most efficient method to do this.

$array = [
    [
        'price' => ['cost' => 200, 'tax' => 10, 'total' => 210],
        'otherKey' => 'etc'
    ],

    [
        'price' => ['cost' => 500, 'tax' => 50, 'total' => 550],
        'otherKey' => 'etc'
    ],
    [
        'price' => ['cost' => 600, 'tax' => 60, 'total' => 660],
        'otherKey' => 'etc'
    ],
];

// desired output is contents of "total" keys:
// [210, 550, 660]

I know this can be done by using nested calls to array_column() or with a basic foreach loop

$result = array_column(array_column($array, 'price'), 'total');

// OR

$result = [];
foreach ($array as $value) {
    $result[] = $value['price']['total'];
}

But I was hoping there was some way to specify a nested key in array_column() like

array_column($array, 'price.total');
like image 615
User97798 Avatar asked Sep 20 '25 12:09

User97798


1 Answers

foreach is better way to do that even you can do a benchmark for performance you can have idea.

like image 126
Ajay Kumar Avatar answered Sep 23 '25 02:09

Ajay Kumar