PHP 在关联数组前面加上文字键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1371016/
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 prepend associative array with literal keys?
提问by Colin Brock
Is it possible to prepend an associative array with literal key=>value pairs? I know that array_unshift() works with numerical keys, but I'm hoping for something that will work with literal keys.
是否可以在关联数组前面加上文字键=> 值对?我知道 array_unshift() 可以使用数字键,但我希望可以使用文字键。
As an example I'd like to do the following:
例如,我想执行以下操作:
$array1 = array('fruit3'=>'apple', 'fruit4'=>'orange');
$array2 = array('fruit1'=>'cherry', 'fruit2'=>'blueberry');
// prepend magic
$resulting_array = ('fruit1'=>'cherry',
'fruit2'=>'blueberry',
'fruit3'=>'apple',
'fruit4'=>'orange');
回答by cletus
Can't you just do:
你不能只做:
$resulting_array = $array2 + $array1;
?
?
回答by PHPguru
The answer is no. You cannot prepend an associative array with a key-value pair.
答案是不。您不能在关联数组之前添加键值对。
However you can create a new array that contains the new key-value pair at the beginning of the array with the union operator +. The outcome is an entirely new array though and creating the new array has O(n) complexity.
但是,您可以使用联合运算符在数组的开头创建一个包含新键值对的新数组+。结果是一个全新的数组,创建新数组的复杂度为 O(n)。
The syntax is below.
语法如下。
$new_array = array('new_key' => 'value') + $original_array;
Note: Do not use array_merge(). array_merge() overwrites keys and does not preserve numeric keys.
注意:不要使用 array_merge()。array_merge() 覆盖键并且不保留数字键。
回答by mvpetrovich
In your situation, you want to use array_merge():
在您的情况下,您想使用 array_merge():
array_merge(array('fruit1'=>'cherry', 'fruit2'=>'blueberry'), array('fruit3'=>'apple', 'fruit4'=>'orange'));
To prepend a single value, for an associative array, instead of array_unshift(), again use array_merge():
要为关联数组添加单个值,而不是 array_unshift(),再次使用 array_merge():
array_merge(array($key => $value), $myarray);
回答by karim79
回答by Bryce Gough
Using the same method as @mvpetrovich, you can use the shorthand version of an array to shorten the syntax.
使用与@mvpetrovich 相同的方法,您可以使用数组的速记版本来缩短语法。
$_array = array_merge(["key1" => "key_value"], $_old_array);
References:
参考:
As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].
从 PHP 5.4 开始,您还可以使用短数组语法,它将 array() 替换为 []。

