Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array mapping in PHP with keys

Tags:

arrays

php

map

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] => [email protected]
    )
    [1] => stdClass Object (
        [id] => 34
        [name] => Ipsum
        [email] => [email protected]
    )
)

And, given 'id' and 'name', produces something like:

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

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.

like image 308
lorenzo-s Avatar asked Aug 21 '12 08:08

lorenzo-s


People also ask

Does array map preserve keys?

The returned array will preserve the keys of the array argument if and only if exactly one array is passed. If more than one array is passed, the returned array will have sequential integer keys.

What is key in PHP array?

key() returns the index element of the current array position.

What are the 3 types of PHP arrays?

In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.

What is PHP array map?

array_map() Function in PHP The array_map() function passes each element of an array to the user-made function and then returns the array after modifying all its elements according to the user made function.


2 Answers

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

like image 78
moonwave99 Avatar answered Oct 08 '22 18:10

moonwave99


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.

like image 28
lorenzo-s Avatar answered Oct 08 '22 18:10

lorenzo-s