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 キー (この例では 1 つ) は動的になります。

4

3 に答える 3

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 に答える