2

说我有这个代码

$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)和 require 键(本例中为一个)将是动态的。

4

3 回答 3

6

像这样的东西:

$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;
于 2014-07-02T15:00:34.863 回答
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')); 

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

于 2014-07-02T15:03:54.017 回答
0

您需要手动执行此操作:

# Insert at offset 2

$offset = 2;
$newArray = array_slice($test, 0, $offset, true) +
            array('yourIndex' => 'def') +
            array_slice($test, $offset, NULL, true);
于 2014-07-02T15:07:49.143 回答