假设我有这个代码
$test = array();
$test['zero'] = 'abc';
$test['two'] = 'ghi';
$test['three'] = 'jkl';
dump($test);
array_splice($test, 1, 0, 'def');
dump($test);
这给了我输出
Array
(
[zero] => abc
[two] => ghi
[three] => jkl
)
Array
(
[zero] => abc
[0] => def
[two] => ghi
[three] => jkl
)
无论如何我可以设置密钥,所以而不是0
它可能是one
?在实际代码中,我需要这个,位置(本例中为 1)和需要键(本例中为 1)将是动态的。
像这样的东西:
$test = array_merge(array_slice($test, 0, 1),
array('one'=>'def'),
array_slice($test, 1, count($test)-1));
或者更短:
$test = array_merge(array_splice($test, 0, 1), array('one'=>'def'), $test);
甚至更短:
$test = array_splice($test, 0, 1) + array('one'=>'def') + $test;
对于 PHP >= 5.4.0:
$test = array_splice($test, 0, 1) + ['one'=>'def'] + $test;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)