Jason Silberman
Jason Silberman

Reputation: 2491

NSArray's valueForKey: equivalent in PHP

In Objective-C there is -[NSArray valueForKey:]. But what is the equivalent in php? I would like something like this:

$things = [['name' => 'Frank', 'age' => 14],'name' => 'bob',['name' => 'Joe', 'age' => '85']];
$names = valueForKey($things, 'name');

I would like $names to be equal to this:

$names = ['Frank', 'Bob', 'Joe'];

How can I do this?

Upvotes: 0

Views: 107

Answers (1)

Cristofor
Cristofor

Reputation: 2097

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

RESULT:

Array
(
    [0] => Frank
    [1] => bob
    [2] => Joe
)

RECURSIVE SOLUTION: Using array_walk_recursive witch executes a callback function for every element in array.

function callback($item, $key){
    if ($key == "name") $names[] = $item;
}
array_walk_recursive($things, 'callback');

print_r($names);

RESULT:

Array
(
    [0] => Frank
    [1] => bob
    [2] => Joe
)

Upvotes: 1

Related Questions