Array mapping in PHP with keys

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

    The easiest way is to use an array_column()

    $result_arr = array_column($arr, 'name', 'id');
    print_r($result_arr );
    
    0 讨论(0)
  • 2020-12-30 05:28

    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.

    0 讨论(0)
  • 2020-12-30 05:30

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

    0 讨论(0)
  • 2020-12-30 05:45

    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

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题