Fastest way to add prefix to array keys?

后端 未结 9 1453
迷失自我
迷失自我 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:47

    I figured out one-line solution:

    array_walk($array, create_function('$value, &$key', '$key = "prefix" . $key;'));
    
    0 讨论(0)
  • 2020-11-28 14:53

    Could do this in one long line I presume:

    $array = array_combine(
        array_map(function($k){ return 'prefix'.$k; }, array_keys($array)),
        $array
    );
    

    Or for versions of PHP prior to 5.3:

    $array = array_combine(
        array_map(create_function('$k', 'return "prefix".$k;'), array_keys($array)),
        $array
    );
    

    There's probably dozens of ways to do this though:

    foreach ($array as $k => $v)
    {
        $array['prefix_'.$k] = $v;
        unset($array[$k]);
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题