Array mapping in PHP with keys

I found I can do:

array_combine(array_map(function($o) { return $o->id; }, $objs), array_map(function($o) { return $o->name; }, $objs));

But it's ugly and requires two whole cycles on the same array.


The easiest way is to use an array_column()

$result_arr = array_column($arr, 'name', 'id');
print_r($result_arr );

Out Put

Array (
    [12] => Lorem
    [34] => Ipsum
)

Just use array_reduce:

$obj1 = new stdClass;
$obj1 -> id = 12;
$obj1 -> name = 'Lorem';
$obj1 -> email = '[email protected]';

$obj2 = new stdClass;
$obj2 -> id = 34;
$obj2 -> name = 'Ipsum';
$obj2 -> email = '[email protected]';

$reduced = array_reduce(
    // input array
    array($obj1, $obj2),
    // fold function
    function(&$result, $item){ 
        // at each step, push name into $item->id position
        $result[$item->id] = $item->name;
        return $result;
    },
    // initial fold container [optional]
    array()
);

It's a one-liner out of comments ^^

Tags:

Php

Arrays

Map