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
)
)
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.
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 ^^
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.
Because your array is array of object then you can call (its like a variable of class) try to call with this:
foreach ($arrays as $object) {
Echo $object->id;
Echo "<br>";
Echo $object->name;
Echo "<br>";
Echo $object->email;
Echo "<br>";
}
Then you can do
// your array of object example $arrays;
$result = array();
foreach ($arrays as $array) {
$result[$array->id] = $array->name;
}
echo "<pre>";
print_r($result);
echo "</pre>";
Sorry I'm answering on handphone. Can't edit the code
The easiest way is to use a LINQ port like YaLinqo library*. It allows performing SQL-like queries on arrays and objects. Its toDictionary
function accepts two callbacks: one returning key of the result array, and one returning value. For example:
$userNamesByIds = from($users)->toDictionary(
function ($u) { return $u->id; },
function ($u) { return $u->name; }
);
Or you can use a shorter syntax using strings, which is equivalent to the above version:
$userNamesByIds = from($users)->toDictionary('$v->id', '$v->name');
If the second argument is omitted, objects themselves will be used as values in the result array.
* developed by me
The easiest way is to use an array_column()
$result_arr = array_column($arr, 'name', 'id');
print_r($result_arr );