Array mapping in PHP with keys

后端 未结 5 1434
日久生厌
日久生厌 2020-12-30 04:59

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:

5条回答
  •  北海茫月
    2020-12-30 05:30

    Just use 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 ^^

提交回复
热议问题