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

前端 未结 4 1655
别那么骄傲
别那么骄傲 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"
    }
    
    0 讨论(0)
  • 2021-02-07 06:40

    This is a clarification on my comment in the accepted method. Hopefully easier to read. This is from a WordPress class, thus the $wpdb reference to write data:

    class SLPlus_Locations {
        private $dbFields = array('name','address','city');
    
        public function MakePersistent() {
            global $wpdb;
            $dataArray = array_reduce($this->dbFields,array($this,'mapPropertyToField'));
            $wpdb->insert('wp_store_locator',$dataArray);
        }
    
        private function mapPropertyToField($result,$property) {
            $result[$property] = $this->$property;
            return $result;
        }
    }
    

    Obviously there is a bit more to the complete solution, but the parts relevant to array_reduce() are present. Easier to read and more elegant than a foreach or forcing the issue through array_map() plus a custom insert statement.

    Nice!

    0 讨论(0)
  • 2021-02-07 06:41

    I had the exact same problem some days ago. It is not possible using array_map, but array_reduce does the trick.

    $arr = array('a','b','c','d');
    $assoc_arr = array_reduce($arr, function ($result, $item) {
        $result[$item] = (($item == 'a') || ($item == 'c')) ? 'yes' : 'no';
        return $result;
    }, array());
    var_dump($assoc_arr);
    

    result:

    array(4) { ["a"]=> string(3) "yes" ["b"]=> string(2) "no" ["c"]=> string(3) "yes" ["d"]=> string(2) "no" }

    0 讨论(0)
  • 2021-02-07 06:42

    As far as I know, it is completely impossible in one expression, so you may as well use a foreach loop, à la

    $new_hash = array();
    
    foreach($original_array as $item) {
        $new_hash[$item] = 'something';
    }
    

    If you need it in one expression, go ahead and make a function:

    function array_map_keys($callback, $array) {
        $result = array();
    
        foreach($array as $item) {
            $r = $callback($item);
    
            $result[$r[0]] = $r[1];
        }
    
        return $result;
    }
    
    0 讨论(0)
提交回复
热议问题