数组映射在PHP中的钥匙 [英] Array mapping in PHP with keys

查看:126
本文介绍了数组映射在PHP中的钥匙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是出于好奇(我知道这可能是一个单行的foreach 语句),是否有一些PHP阵列功能(或多个组合),鉴于像数组

Just for curiosity (I know it can be a single line foreach statement), is there some PHP array function (or a combination of many) that given an array like:

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

而且,鉴于ID'名称',产生类似:

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

我使用这个模式很多,我注意到 array_map 在这种情况下很没用,因为你不能指定返回数组的键。

I use this pattern a lot, and I noticed that array_map is quite useless in this scenario cause you can't specify keys for returned array.

推荐答案

只需使用 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()
);

这是一个班轮出的意见^^

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

这篇关于数组映射在PHP中的钥匙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆