2

I have an array called $friends with names and ids, gotten from the Facebook graph API.

If I print it, it look something like this:

Array (
  [0] => Array (
     [name] => Tom
     [id] => 21)
  [1] => Array (
     [name] => Bob
     [id] => 22)
)

How do I retrieve all Keys (ids) and create a new array like this one?

Array ( [0] => 21 [1] => 22 )
kba
  • 19,333
  • 5
  • 62
  • 89
lisovaccaro
  • 32,502
  • 98
  • 258
  • 410

4 Answers4

8
$ids = array_map(function ($friend) { return $friend['id']; }, $friends);

Note, uses PHP 5.3+ anonymous function syntax.

deceze
  • 510,633
  • 85
  • 743
  • 889
2

You can use a simple foreach.

$ids = array();
foreach($friends as $friend)
   $ids[] = $friend['id'];
Aurelio De Rosa
  • 21,856
  • 8
  • 48
  • 71
0
foreach ($friends as $key => $value) {

    $newFriends[$key] = $value['id'];
}
Steve Robbins
  • 13,672
  • 12
  • 76
  • 124
0
$arFinal = array();
foreach ($friends as $key => $val){
    $arFinal[$key] = $val['id'];
}
Justin
  • 84,773
  • 49
  • 224
  • 367
Poonam Bhatt
  • 10,154
  • 16
  • 53
  • 72