2

I Have a nested array with the structure:

[ 1 => [ 
        id => id1,
        label => value1
       ]
  2 => [ 
        id => id2,
        label => value2
       ]
]

And I'm trying to get an array with the structure

[
 id1 => value1,
 id2 => value2
]

Currently, this loop works just fine.

$length = count($array);
$sortedArray = [];
    for ($i = 0; $i < $length ; $i++) {
        $id = $array[$i]['id'];
        $value = $array[$i]['label'];
        $sortedArray[$id] = $value;
    }

But I'm trying to refactor it using a PHP array mapping or filtering function. I'm shooting for something like the function below, but it isn't working because I don't think I can pass $sortedArray into the mapping function.

$sortedArray = [];
array_map(function($index) {
       $sortedArray[$index['id']] = $index['label'];
    }, $array);

How can my loop be refactored?

SpaceJam
  • 536
  • 5
  • 12
  • 5
    Look at `array_column()`. – Rizier123 Aug 03 '16 at 18:15
  • 3
    `$result = array_column($array, 'label', 'id');` – Mark Baker Aug 03 '16 at 18:17
  • Yep! [array_column](http://php.net/manual/en/function.array-column.php) was exactly what I needed. – SpaceJam Aug 03 '16 at 18:32
  • I can see how this could be a borderline duplicate @Rizier123, but I would argue that I am asking for a associative array for an answer instead of an indexed array and that this answer requires using `array_column()` with an extra argument which is not exemplified in the other answer. – SpaceJam Aug 05 '16 at 17:30
  • This kind of question is asked quite often. And even your case is covered inside the dupe: http://stackoverflow.com/a/27954965/3933332 even with a implementation for PHP <5.5. – Rizier123 Aug 05 '16 at 17:31

0 Answers0