phparraysmultidimensional-arrayflattenarray-column

Get column values from third level of a multidimensional array


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.


Solution

  • 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]