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

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


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" }


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;}


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!