2

I'm looking for a more professional method to solve a very simple problem.

I have an array like :

$originalArray = [
    0 => [
        'id' => 22,
    ],
    1 => [
        'id' => 9,
    ],
    2 => [
        'id' => 15,
    ],  
]

Knowing all those ids are unique, I want to simplify the array to something like:

$peeledResult = [
    0 => 22,
    1=> 9,
    2 => 15,
]

The following is my basic solution for it but I was wondering if there is a more elegant method to achieve the same.

$peeledResult = [];
foreach ($originalArray as $item) {
    $peeledResult[] = $role['id'];
}

Thanks for any advice in advance :)

Ali
  • 2,993
  • 3
  • 19
  • 42
  • Great, thanks @Rizier123. Just to confirm the `array_column()` method mentioned in [one of the answers](http://stackoverflow.com/a/15720619/4960774) does the job perfectly! – Ali Jul 14 '15 at 08:18

1 Answers1

3

Try with array_column (Return the values from a single column in the input array)

$new = array_column($originalArray, 'id');

Or array_map -

$new = array_map(function($x) {
  return $x['id'];
}, $originalArray);

Output

array(3) {
  [0]=>
  int(22)
  [1]=>
  int(9)
  [2]=>
  int(15)
}
kamal pal
  • 4,187
  • 5
  • 25
  • 40
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
  • Thanks @b0s3, sorry i was a bit late to accept your answer before the question flagged as duplicated. – Ali Jul 14 '15 at 08:11
  • But to be fair the `array_column()` method offered in the other question does the job much cleaner, so thanks to @Rizier123 too ;) – Ali Jul 14 '15 at 08:16