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
What I'm looking for ultimately is an array of only the ages of all four.
age: array(10,15,12,8)
Can this be achieved without using a foreach loop? I tried a mix of array_column and array_values but somehow I get the same array back.
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);
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.