使用自定义键进行阵列拼接

时间:2014-07-02 14:54:12

标签: 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);

这给了我输出

Array
(
    [zero] => abc
    [two] => ghi
    [three] => jkl
)

Array
(
    [zero] => abc
    [0] => def
    [two] => ghi
    [three] => jkl
)

无论如何我可以设置密钥,因此0代替one而不是{{1}}?在我需要的实际代码中,位置(本例中为1)和require键(本例中为1)将是动态的。

3 个答案:

答案 0 :(得分:5)

这样的事情:

$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;

答案 1 :(得分:2)

function array_insert (&$array, $position, $insert_array) { 
  $first_array = array_splice ($array, 0, $position); 
  $array = array_merge ($first_array, $insert_array, $array); 
} 

array_insert($test, 1, array ('one' => 'def')); 

in:http://php.net/manual/en/function.array-splice.php

答案 2 :(得分:0)

您需要手动执行此操作:

# Insert at offset 2

$offset = 2;
$newArray = array_slice($test, 0, $offset, true) +
            array('yourIndex' => 'def') +
            array_slice($test, $offset, NULL, true);