Fastest way to add prefix to array keys?

后端 未结 9 1503
迷失自我
迷失自我 2020-11-28 14:29

What is the fastest way to add string prefixes to array keys?

Input

$array = array(
 \'1\' => \'val1\',
 \'2\' => \'val2\',
);
<
9条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 14:57

    function keyprefix($keyprefix, Array $array) {
    
        foreach($array as $k=>$v){
            $array[$keyprefix.$k] = $v;
            unset($array[$k]);
        }
    
        return $array; 
    }
    

    Using array_flip will not preserve empty or null values. Additional code could be added in the unlikely event that the prefixed key already exists.

提交回复
热议问题