Array mapping in PHP with keys

后端 未结 5 1440
日久生厌
日久生厌 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:48

    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

提交回复
热议问题