NSArray的valueForKey:PHP中的等价物

时间:2014-06-07 19:46:02

标签: php objective-c arrays nsarray

在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'];

我该怎么做?

1 个答案:

答案 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
)