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

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

提交回复
热议问题