如何在 PHP 中的数组开头插入一个项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1739706/
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
How to insert an item at the beginning of an array in PHP?
提问by web
I know how to insert it to the end by:
我知道如何通过以下方式将其插入到最后:
$arr[] = $item;
But how to insert it to the beginning?
但是如何将它插入到开头呢?
回答by Trav L
Use array_unshift($array, $item);
使用array_unshift($array, $item);
$arr = array('item2', 'item3', 'item4');
array_unshift($arr , 'item1');
print_r($arr);
will give you
会给你
Array
(
[0] => item1
[1] => item2
[2] => item3
[3] => item4
)
回答by tihe
In case of an associative array or numbered array where you do not want to change the array keys:
如果您不想更改数组键的关联数组或编号数组:
$firstItem = array('foo' => 'bar');
$arr = $firstItem + $arr;
array_mergedoes not work as it always reindexes the array.
array_merge不起作用,因为它总是重新索引数组。
回答by MaxiWheat
Use function array_unshift
使用功能 array_unshift
回答by Manish Dhruw
Insert an item in the beginning of an associative array with string/custom index key
使用字符串/自定义索引键在关联数组的开头插入一个项目
<?php
$array = ['keyOne'=>'valueOne', 'keyTwo'=>'valueTwo'];
$array = array_reverse($array);
$array['newKey'] = 'newValue';
$array = array_reverse($array);
RESULT
结果
[
'newKey' => 'newValue',
'keyOne' => 'valueOne',
'keyTwo' => 'valueTwo'
]
回答by DarthVader
This will help
这将有助于
http://www.w3schools.com/php/func_array_unshift.asp
http://www.w3schools.com/php/func_array_unshift.asp
array_unshift();
回答by Vinit Kadkol
Use array_unshift()to insert the first element in an array.
使用array_unshift()插入数组中的第一个元素。
User array_shift()to removes the first element of an array.
用户array_shift()删除数组的第一个元素。
回答by Arnas Pe?elis
Or you can use temporary array and then delete the real one if you want to change it while in cycle:
或者,如果您想在循环中更改它,您可以使用临时数组,然后删除真正的数组:
$array = array(0 => 'a', 1 => 'b', 2 => 'c');
$temp_array = $array[1];
unset($array[1]);
array_unshift($array , $temp_array);
the output will be:
输出将是:
array(0 => 'b', 1 => 'a', 2 => 'c')
and when are doing it while in cycle, you should clean $temp_arrayafter appending item to array.
并且在循环中执行此操作时,应$temp_array在将项目附加到数组后进行清理。
回答by Timothy Nwanwene
With custom index:
使用自定义索引:
$arr=array("a"=>"one", "b"=>"two");
$arr=array("c"=>"three", "d"=>"four").$arr;
print_r($arr);
-------------------
output:
----------------
Array
(
[c]=["three"]
[d]=["four"]
[a]=["two"]
[b]=["one"]
)
回答by pictoru
For an associative array you can just use merge.
对于关联数组,您可以只使用合并。
$arr = array('item2', 'item3', 'item4');
$arr = array_merge(array('item1'), $arr)

