TMH*_*TMH 1 php arrays array-splice
说我有这个代码
$test = array();
$test['zero'] = 'abc';
$test['two'] = 'ghi';
$test['three'] = 'jkl';
dump($test);
array_splice($test, 1, 0, 'def');
dump($test);
Run Code Online (Sandbox Code Playgroud)
这给了我输出
Array
(
[zero] => abc
[two] => ghi
[three] => jkl
)
Array
(
[zero] => abc
[0] => def
[two] => ghi
[three] => jkl
)
Run Code Online (Sandbox Code Playgroud)
无论如何我可以设置密钥,所以0可能不是one吗?在我需要的实际代码中,位置(本例中为1)和require键(本例中为1)将是动态的.
像这样的东西:
$test = array_merge(array_slice($test, 0, 1),
array('one'=>'def'),
array_slice($test, 1, count($test)-1));
Run Code Online (Sandbox Code Playgroud)
或更短:
$test = array_merge(array_splice($test, 0, 1), array('one'=>'def'), $test);
Run Code Online (Sandbox Code Playgroud)
更短:
$test = array_splice($test, 0, 1) + array('one'=>'def') + $test;
Run Code Online (Sandbox Code Playgroud)
对于PHP> = 5.4.0:
$test = array_splice($test, 0, 1) + ['one'=>'def'] + $test;
Run Code Online (Sandbox Code Playgroud)