在Objective-C中有-[NSArray valueForKey:]
。但是什么是PHP的等价物?我想要这样的东西:
$things = [['name' => 'Frank', 'age' => 14],'name' => 'bob',['name' => 'Joe', 'age' => '85']];
$names = valueForKey($things, 'name');
我希望$names
与此相同:
$names = ['Frank', 'Bob', 'Joe'];
我该怎么做?
答案 0 :(得分:1)
$things = array(array('name' => 'Frank', 'age' => 14),array('name' => 'bob'),array('name' => 'Joe', 'age' => '85'));
$names = array();
foreach ($things as $item) {
foreach ($item as $key => $value) {
if ($key == "name") {
$names[] = $value;
}
}
}
print_r($names);
结果:
Array
(
[0] => Frank
[1] => bob
[2] => Joe
)
回归解决方案:
使用array_walk_recursive
对数组中的每个元素执行回调函数。
function callback($item, $key){
if ($key == "name") $names[] = $item;
}
array_walk_recursive($things, 'callback');
print_r($names);
结果:
Array
(
[0] => Frank
[1] => bob
[2] => Joe
)