PHP 中关联数组中最内层值的数组

Array of inner most values in associative array in PHP

I have an Array of the form-
$description: array(2)
  0: array(2)
    0: 
       name: john
       age: 10
    1: 
       name: mary
       age: 15
  1: array(2)
    0: 
       name: mark
       age: 12
    1: 
       name: susan
       age: 8

我要找的最终是一个只包含所有四个人年龄的数组。

age: array(10,15,12,8)

不使用 foreach 循环可以实现吗?我尝试了 array_column 和 array_values 的混合,但不知何故我得到了相同的数组。

flattening数组然后mapping数组的示例。

<?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);

您可以使用 array_walk 来做到这一点


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