使用键在PHP中进行数组映射

lor*_*o-s 10 php arrays map

只是为了好奇(我知道它可以是单行foreach语句),是否有一些给定数组的PHP数组函数(或许多组合):

Array (
    [0] => stdClass Object (
        [id] => 12
        [name] => Lorem
        [email] => lorem@example.org
    )
    [1] => stdClass Object (
        [id] => 34
        [name] => Ipsum
        [email] => ipsum@example.org
    )
)
Run Code Online (Sandbox Code Playgroud)

并且,给出'id''name'产生类似的东西:

Array (
    [12] => Lorem
    [34] => Ipsum
)
Run Code Online (Sandbox Code Playgroud)

我经常使用这个模式,并且我注意到array_map在这种情况下这是无用的,因为你无法为返回的数组指定键.

moo*_*e99 23

只需使用array_reduce:

$obj1 = new stdClass;
$obj1 -> id = 12;
$obj1 -> name = 'Lorem';
$obj1 -> email = 'lorem@example.org';

$obj2 = new stdClass;
$obj2 -> id = 34;
$obj2 -> name = 'Ipsum';
$obj2 -> email = 'ipsum@example.org';

$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()
);
Run Code Online (Sandbox Code Playgroud)

这是评论中的单行^^


lor*_*o-s 5

我发现我可以做到:

array_combine(array_map(function($o) { return $o->id; }, $objs), array_map(function($o) { return $o->name; }, $objs));
Run Code Online (Sandbox Code Playgroud)

但它很丑陋,并且需要在同一个阵列上进行两个完整的周期。