How to convert an array of arrays or objects to an associative array?

前端 未结 4 1703
别那么骄傲
别那么骄傲 2021-02-07 05:59

I\'m used to perl\'s map() function where the callback can assign both the key and the value, thus creating an associative array where the input was a flat array. I\'m aware of

4条回答
  •  耶瑟儿~
    2021-02-07 06:32

    A good use case of yield operator!

    $arr = array('a','b','c','d');
    
    $fct = function(array $items) {
                foreach($items as $letter)
                {
                    yield sprintf("key-%s",
                        $letter
                    ) => "yes";
                }
            };
    
    $newArr = iterator_to_array($fct($arr));
    

    which gives:

    array(4) {
      'key-a' =>
      string(3) "yes"
      'key-b' =>
      string(3) "yes"
      'key-c' =>
      string(3) "yes"
      'key-d' =>
      string(3) "yes"
    }
    

提交回复
热议问题