Array mapping in PHP with keys

匿名 (未验证) 提交于 2019-12-03 01:48:02

问题:

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.

回答1:

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



回答2:

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.



回答3:

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 "
"; Echo $object->name; Echo "
"; Echo $object->email; Echo "
"; }

Then you can do

 // your array of object example $arrays;  $result = array();  foreach ($arrays as $array) {        $result[$array->id] = $array->name;  }     echo "
";    print_r($result);    echo "
";

Sorry I'm answering on handphone. Can't edit the code



回答4:

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',  
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!