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


当前回答

要将元素插入到具有字符串键的数组中,您可以这样做:

/* insert an element after given array key
 * $src = array()  array to work with
 * $ins = array() to insert in key=>array format
 * $pos = key that $ins will be inserted after
 */ 
function array_insert_string_keys($src,$ins,$pos) {

    $counter=1;
    foreach($src as $key=>$s){
        if($key==$pos){
            break;
        }
        $counter++;
    } 

    $array_head = array_slice($src,0,$counter);
    $array_tail = array_slice($src,$counter);

    $src = array_merge($array_head, $ins);
    $src = array_merge($src, $array_tail);

    return($src); 
} 

其他回答

如何使用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

你可以用这个

foreach ($array as $key => $value) 
{
    if($key==1)
    {
        $new_array[]=$other_array;
    }   
    $new_array[]=$value;    
}

如果你想保留初始数组的键,并添加一个有键的数组,那么使用下面的函数:

function insertArrayAtPosition( $array, $insert, $position ) {
    /*
    $array : The initial array i want to modify
    $insert : the new array i want to add, eg array('key' => 'value') or array('value')
    $position : the position where the new array will be inserted into. Please mind that arrays start at 0
    */
    return array_slice($array, 0, $position, TRUE) + $insert + array_slice($array, $position, NULL, TRUE);
}

电话的例子:

$array = insertArrayAtPosition($array, array('key' => 'Value'), 3);
function insert(&$arr, $value, $index){       
    $lengh = count($arr);
    if($index<0||$index>$lengh)
        return;

    for($i=$lengh; $i>$index; $i--){
        $arr[$i] = $arr[$i-1];
    }

    $arr[$index] = $value;
}

你可能会觉得这更直观一些。它只需要调用array_splice一个函数:

$original = array( 'a', 'b', 'c', 'd', 'e' );
$inserted = array( 'x' ); // not necessarily an array, see manual quote
 
array_splice( $original, 3, 0, $inserted ); // splice in at position 3
// $original is now a b c x d e

如果replacement只是一个元素,则没有必要在它周围加上array(),除非该元素本身是数组、对象或NULL。

RETURN VALUE:需要注意的是,函数不返回所需的替换。$original通过引用传递,并在适当的位置进行编辑。请参阅参数列表中带有&的表达式array &$array。