如何将一个新项目插入到数组的任何位置,例如在数组的中间?


当前回答

如何使用array_splice()保存数组键

@jay的答案。Lee是正确的,不幸的是,它不能保存数组的键,正如评论中指出的那样:

$original = array( 
    'a' => 'A', 
    'b' => 'B', 
    'c' => 'C', 
    // insert here
    'd' => 'D', 
    'e' => 'E');

$inserted = array( 'x' => 'X' ); 

array_splice( $original, 3, 0, $inserted );
print_r($original);

/* Output
Array
(
    [a] => A
    [b] => B
    [c] => C
    [0] => X  <= the lost key 
    [d] => D
    [e] => E
) */

我发现保存数组键的最简单的方法是使用array_splice()函数,并使用+ /联合操作符将数组添加在一起(也在另一个答案的评论中提到):

$original = array( 
    'a' => 'A', 
    'b' => 'B', 
    'c' => 'C', 
    // insert here
    'd' => 'D', 
    'e' => 'E');

$inserted = array( 'x' => 'X' ); 

// Insert before postion 'd'
$before = array_splice( $original, 0, 3 ); // $original contains the left over

// Merge together
$result = $before + $inserted + $original;
print_r($result);

/* Output
Array
(
    [a] => A
    [b] => B
    [c] => C
    [x] => X
    [d] => D
    [e] => E
) */

注意:使用数组联合操作符仅在处理非数字键时是安全的


谢谢你的更正@mickmackusa

其他回答

基于@Halil的伟大回答,这里是一个简单的函数如何在特定的键后插入新元素, 同时保留整型键:

private function arrayInsertAfterKey($array, $afterKey, $key, $value){
    $pos   = array_search($afterKey, array_keys($array));

    return array_merge(
        array_slice($array, 0, $pos, $preserve_keys = true),
        array($key=>$value),
        array_slice($array, $pos, $preserve_keys = true)
    );
} 

没有本地PHP函数(据我所知)可以完全完成您的请求。

我已经写了2个我认为适合目的的方法:

function insertBefore($input, $index, $element) {
    if (!array_key_exists($index, $input)) {
        throw new Exception("Index not found");
    }
    $tmpArray = array();
    $originalIndex = 0;
    foreach ($input as $key => $value) {
        if ($key === $index) {
            $tmpArray[] = $element;
            break;
        }
        $tmpArray[$key] = $value;
        $originalIndex++;
    }
    array_splice($input, 0, $originalIndex, $tmpArray);
    return $input;
}

function insertAfter($input, $index, $element) {
    if (!array_key_exists($index, $input)) {
        throw new Exception("Index not found");
    }
    $tmpArray = array();
    $originalIndex = 0;
    foreach ($input as $key => $value) {
        $tmpArray[$key] = $value;
        $originalIndex++;
        if ($key === $index) {
            $tmpArray[] = $element;
            break;
        }
    }
    array_splice($input, 0, $originalIndex, $tmpArray);
    return $input;
}

虽然速度更快,而且可能更节省内存,但这只适用于不需要维护数组键的地方。

如果你确实需要维护密钥,下面的方法会更合适;

function insertBefore($input, $index, $newKey, $element) {
    if (!array_key_exists($index, $input)) {
        throw new Exception("Index not found");
    }
    $tmpArray = array();
    foreach ($input as $key => $value) {
        if ($key === $index) {
            $tmpArray[$newKey] = $element;
        }
        $tmpArray[$key] = $value;
    }
    return $input;
}

function insertAfter($input, $index, $newKey, $element) {
    if (!array_key_exists($index, $input)) {
        throw new Exception("Index not found");
    }
    $tmpArray = array();
    foreach ($input as $key => $value) {
        $tmpArray[$key] = $value;
        if ($key === $index) {
            $tmpArray[$newKey] = $element;
        }
    }
    return $tmpArray;
}

如何使用array_splice()保存数组键

@jay的答案。Lee是正确的,不幸的是,它不能保存数组的键,正如评论中指出的那样:

$original = array( 
    'a' => 'A', 
    'b' => 'B', 
    'c' => 'C', 
    // insert here
    'd' => 'D', 
    'e' => 'E');

$inserted = array( 'x' => 'X' ); 

array_splice( $original, 3, 0, $inserted );
print_r($original);

/* Output
Array
(
    [a] => A
    [b] => B
    [c] => C
    [0] => X  <= the lost key 
    [d] => D
    [e] => E
) */

我发现保存数组键的最简单的方法是使用array_splice()函数,并使用+ /联合操作符将数组添加在一起(也在另一个答案的评论中提到):

$original = array( 
    'a' => 'A', 
    'b' => 'B', 
    'c' => 'C', 
    // insert here
    'd' => 'D', 
    'e' => 'E');

$inserted = array( 'x' => 'X' ); 

// Insert before postion 'd'
$before = array_splice( $original, 0, 3 ); // $original contains the left over

// Merge together
$result = $before + $inserted + $original;
print_r($result);

/* Output
Array
(
    [a] => A
    [b] => B
    [c] => C
    [x] => X
    [d] => D
    [e] => E
) */

注意:使用数组联合操作符仅在处理非数字键时是安全的


谢谢你的更正@mickmackusa

$a = array(1, 2, 3, 4);
$b = array_merge(array_slice($a, 0, 2), array(5), array_slice($a, 2));
// $b = array(1, 2, 5, 3, 4)

在做了几天之后,这是我能找到的最简单的解决方案。

$indexnumbertoaddat // this is a variable that points to the index # where you 
want the new array to be inserted

$arrayToAdd = array(array('key' => $value, 'key' => $value)); //this is the new 
 array and it's values that you want to add. //the key here is to write it like 
 array(array('key' =>, since you're adding this array inside another array. This 
 is the point that a lot of answer left out. 

array_splice($originalArray, $indexnumbertoaddatt, 0, $arrayToAdd); //the actual 
splice function. You're doing it to $originalArray, at the index # you define, 
0 means you're just shifting all other index items down 1, and then you add the 
new array.