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

前端 未结 4 1653
别那么骄傲
别那么骄傲 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: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" }

提交回复
热议问题