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,080
  • 5
  • 59
  • 87
lisovaccaro
  • 30,232
  • 96
  • 246
  • 398

4 Answers4

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

Note, uses PHP 5.3+ anonymous function syntax.

deceze
  • 491,798
  • 79
  • 706
  • 853
2

You can use a simple foreach.

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

    $newFriends[$key] = $value['id'];
}
Steve Robbins
  • 13,266
  • 10
  • 73
  • 122
0
$arFinal = array();
foreach ($friends as $key => $val){
    $arFinal[$key] = $val['id'];
}
Justin
  • 82,493
  • 48
  • 216
  • 356
Poonam Bhatt
  • 9,890
  • 16
  • 48
  • 70