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.
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.
key() returns the index element of the current array position.
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.
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.
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 ^^
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With