php 为数组键添加前缀的最快方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2607595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fastest way to add prefix to array keys?
提问by Kirzilla
What is the fastest way to add string prefixes to array keys?
将字符串前缀添加到数组键的最快方法是什么?
Input
输入
$array = array(
'1' => 'val1',
'2' => 'val2',
);
Needed output:
需要的输出:
$array = array(
'prefix1' => 'val1',
'prefix2' => 'val2',
);
采纳答案by Kendall Hopkins
I've found that PHPBench is not a very good source for non-trivial benchmarks. So unless your actually interested in running for(....);it's not going to correctly show which syntax will be faster. I've put together a simple benchmark to show that foreach is actually the fastest when your use both the key and value during the iteration.
我发现 PHPBench 不是非平凡基准测试的好来源。因此,除非您真的对运行感兴趣,否则for(....);它不会正确显示哪种语法会更快。我已经整理了一个简单的基准测试,以表明当您在迭代期间同时使用键和值时,foreach 实际上是最快的。
It's very important to actually force PHP to read the values from a loop iteration, or else it'll do its best to optimize them out. In the example below I use the doNothingfunction to force PHP to calculate the key and value each time. Using doNothing will cause an overhead to be applied to each loop, but it will be the same for each loop since the number of calls will be the same.
实际上强制 PHP 从循环迭代中读取值非常重要,否则它会尽力优化它们。在下面的示例中,我使用该doNothing函数强制 PHP 每次计算键和值。使用 doNothing 将导致对每个循环应用开销,但每个循环的开销相同,因为调用次数相同。
I wasn't really that surprised that foreachcame out on top since it's the language construct for iterating a dictionary.
我并不感到惊讶,foreach因为它是迭代字典的语言结构。
$array = range( 0, 1000000 );
function doNothing( $value, $key ) {;}
$t1_start = microtime(true);
foreach( $array as $key => $value ) {
doNothing( $value, $key );
}
$t1_end = microtime(true);
$t2_start = microtime(true);
$array_size = count( $array );
for( $key = 0; $key < $array_size; $key++ ) {
doNothing( $array[$key], $key );
}
$t2_end = microtime(true);
//suggestion from PHPBench as the "fastest" way to iterate an array
$t3_start = microtime(true);
$key = array_keys($array);
$size = sizeOf($key);
for( $i=0; $i < $size; $i++ ) {
doNothing( $key[$i], $array[$key[$i]] );
}
$t3_end = microtime(true);
$t4_start = microtime(true);
array_walk( $array, "doNothing" );
$t4_end = microtime(true);
print
"Test 1 ".($t1_end - $t1_start)."\n". //Test 1 0.342370986938
"Test 2 ".($t2_end - $t2_start)."\n". //Test 2 0.369848966599
"Test 3 ".($t3_end - $t3_start)."\n". //Test 3 0.78616809845
"Test 4 ".($t4_end - $t4_start)."\n"; //Test 4 0.542922019958
Edit: I'm using PHP 5.3 on 64-bit Mac OSX 10.6
编辑:我在 64 位 Mac OSX 10.6 上使用 PHP 5.3
回答by Lode
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:
或者对于 5.3 之前的 PHP 版本:
$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]);
}
回答by mistajolly
function keyprefix($keyprefix, Array $array) {
foreach($array as $k=>$v){
$array[$keyprefix.$k] = $v;
unset($array[$k]);
}
return $array;
}
Using array_flipwill not preserve empty or null values.
Additional code could be added in the unlikely event that the prefixed key already exists.
使用array_flip不会保留空值或空值。如果前缀键已经存在,则可以添加额外的代码。
回答by codaddict
If you don't want to use for loop you can do:
如果您不想使用 for 循环,您可以执行以下操作:
// function called by array_walk to change the $value in $key=>$value.
function myfunction(&$value,$key) {
$value="prefix$value";
}
$keys = array_keys($array); // extract just the keys.
array_walk($keys,"myfunction"); // modify each key by adding a prefix.
$a = array_combine($keys,array_values($array)); // combine new keys with old values.
I don't think this will be more efficient than the forloop. I guess array_walk will internally use a loop and there is also the function call overhead here.
我认为这不会比for循环更有效。我猜 array_walk 将在内部使用一个循环,这里还有函数调用开销。
回答by adamS
Another way to do achieve is with array_flip()
另一种实现方法是使用 array_flip()
<?php
$data = array_flip($data);
foreach($data as $key => &$val) { $val = "prefix" . $val; }
$data = array_flip($data);
回答by Alpesh Patel
function array_key_prefix_suffix(&$array,$prefix='',$suffix=''){
$key_array = array_keys($array);
$key_string = $prefix.implode($suffix.','.$prefix,$key_array).$suffix;
$key_array = explode(',', $key_string);
$array = array_combine($key_array, $array);
}
This is implemented and working very well
这已实施并且运行良好
回答by Alpesh Patel
Here's a fast, one-liner solution (supported on PHP 4+) to add a prefix and/or suffix using implode / explode:
这是使用内爆/爆炸添加前缀和/或后缀的快速单行解决方案(PHP 4+ 支持):
$array = range(0, 1000000);
$delimiter = '-';
$prefix = 'string';
$suffix = '';
$result = array_combine(explode($delimiter, $prefix . implode($suffix . $delimiter . $prefix, array_keys($array)) . $suffix), $array);
回答by TarranJones
I would create a completely new array, and create your new keys. That has to be faster than unsetting all unwanted keys;
我会创建一个全新的数组,并创建您的新密钥。这必须比取消设置所有不需要的键更快;
$prefixed_array = array();
foreach ($array as $key => $value) {
$prefixed_array[ $prefix . $key] = $value;
}
And if you want to do any other "affix"'s
如果你想做任何其他的“词缀”
function array_affix_keys($affix, Array $array, $type = 'prefix', $options = array()){
$affixed_array = array();
if($type =='prefix'){
foreach ($array as $key => $value) {$affixed_array[ $affix . $key] = $value;}
return $affixed_array;
}
if($type =='suffix'){
foreach ($array as $key => $value) {$affixed_array[$key . $affix ] = $value;}
return $affixed_array;
}
if($type =='circumfix'){
if(is_array($affix) && count($affix) == 2){
foreach ($array as $key => $value) {
$affixed_array[ $affix[0] . $key . $affix[1] ] = $value;
}
}
return $affixed_array;
}
if($type == 'simulfix' && isset($options['phonemes'])){
foreach ($array as $key => $value) { $affixed_array[ str_replace($options['phonemes'], $affix, $key) ] = $value;}
return $affixed_array;
}
return $array;
}
$prefixed = array_affix_keys('prefix_', $array);
$prefixed = array_affix_keys('prefix_', $array, 'prefix');
$suffixed = array_affix_keys('_suffix', $array, 'suffix');
$circumfixed = array_affix_keys(array('prefix', 'suffix'), $array, 'circumfix');
$simulfix = array_affix_keys('replace', $array, 'simulfix', array('phonemes' => 'find'));
回答by fracz
I figured out one-line solution:
我想出了一行解决方案:
array_walk($array, create_function('$value, &$key', '$key = "prefix" . $key;'));

