1

I want to get all of the values from an array with 3 levels where the key is age. How can I extract a column of data from a three dimensional array without using a foreach() loop?

My input array:

$description = [
    [
        ['name' => 'john', 'age' => 10],
        ['name' => 'mary', 'age' => 15],
    ],
    [
        ['name' => 'mark', 'age' => 12],
        ['name' => 'susan', 'age' => 8],
    ]
];

Desired result:

[10, 15, 12, 8]

I tried a mix of array_column() and array_values() but somehow I get the same array back.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
manishk
  • 526
  • 8
  • 26
  • You'll have to loop in some way or other ... if you don't like an explicit loop, then use `array_walk` or something for that part. – CBroe Jan 10 '22 at 10:43

3 Answers3

3

You may use array_walk to do that


$array = [
    [
        [
            'name' => 'john',
            'age' => 10,
        ],
        [
            'name' => 'marry',
            'age' => 15,
        ]
    ],
    [
        [
            'name' => 'mark',
            'age' => 12,
        ],
        [
            'name' => 'susan',
            'age' => 8,
        ]
    ],
];

$ages = [];
array_walk_recursive($array, function($value, $key) use(&$ages) {
    if( $key == 'age' ) {
        $ages[] = $value;
    }
});

print_r($ages); // result [10, 15, 12, 8]


Debuqer
  • 328
  • 2
  • 7
1

An example by flattening the array and then mapping the array.

<?php

$array = [
    [
        ['name' => 'john',  'age' => 10,],
        ['name' => 'mary', 'age' => 15,],
    ],
    [
        ['name' => 'mark',  'age' => 12,],
        ['name' => 'susan', 'age' => 8,],
    ]
];

$flatten_array = array_merge(...$array);

$output = array_map(function ($item) {
    return $item['age'];
}, $flatten_array);

var_dump($output);
ikhvjs
  • 5,316
  • 2
  • 13
  • 36
0

Use a flattening technique to reduce the array's complexity from 3 levels to just 2 levels. Then extract the age column from that 2d array.

Code: (Demo)

var_export(
    array_column(
        array_merge(...$array),
        'age'
    )
);

This approach is more direct than array_walk_recursive() because that function will visit every non-array data point (leaf-node) -- this means that each encountered element must be checked if it qualifies to be pushed into the result array.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136