PHP:向数组值添加前缀字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4535846/
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
PHP: Adding prefix strings to array values
提问by skeggse
What is the best way to add a specific value or values to an array? Kinda hard to explain, but this should help:
将一个或多个特定值添加到数组的最佳方法是什么?有点难以解释,但这应该会有所帮助:
<?php
$myarray = array("test", "test2", "test3");
$myarray = array_addstuff($myarray, " ");
var_dump($myarray);
?>
Which outputs:
哪些输出:
array(3) {
[0]=>
string(5) " test"
[1]=>
string(6) " test2"
[2]=>
string(6) " test3"
}
You could do so like this:
你可以这样做:
function array_addstuff($a, $i) {
foreach ($a as &$e)
$e = $i . $e;
return $a;
}
But I'm wondering if there's a faster way, or if this function is built-in.
但我想知道是否有更快的方法,或者这个函数是否是内置的。
回答by Andre
In the case that you're using a PHP version >= 5.3:
如果您使用的是 PHP 版本 >= 5.3:
$array = array('a', 'b', 'c');
array_walk($array, function(&$value, $key) { $value .= 'd'; } );
回答by shfx
Use array_map()
$array = array('a', 'b', 'c');
$array = array_map(function($value) { return ' '.$value; }, $array);
回答by manish
Below code will add "prefix_" as a prefix to each element value:
下面的代码将添加“prefix_”作为每个元素值的前缀:
$myarray = array("test", "test2", "test3");
$prefixed_array = preg_filter('/^/', 'prefix_', $myarray);
Output will be:
输出将是:
Array ( [0] => prefix_test [1] => prefix_test2 [2] => prefix_test3 )
回答by Oswald
Use array_walk. In PHP 5.3 you can use an anonymous to define that callback. Because you want to modify the actual array, you have to specify the first parameter of the callback as pass-by-reference.
使用array_walk。在 PHP 5.3 中,您可以使用匿名来定义该回调。因为要修改实际数组,所以必须将回调的第一个参数指定为传递引用。