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

前端 未结 4 1656
别那么骄傲
别那么骄傲 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: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!

提交回复
热议问题