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


当前回答

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

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 insert element on position
 * 
 * @link https://vector.cool
 * 
 * @since 1.01.38
 *
 * @param array $original
 * @param mixed $inserted
 * @param int   $position
 * @return array
 */
function array_insert(&$original, $inserted, int $position): array
{
    array_splice($original, $position, 0, array($inserted));
    return $original;
}


$columns = [
    ['name' => '預約項目', 'column' => 'item_name'],
    ['name' => '預約時間', 'column' => 'start_time'],
    ['name' => '預約姓名', 'column' => 'full_name'],
    ['name' => '連絡電話', 'column' => 'phone'],
    ['name' => '建立時間', 'column' => 'create_time']
];
$col = ['name' => '預約帳戶', 'column' => 'user_id'];
$columns = array_insert($columns, $col, 3);
print_r($columns);

打印:

Array
(
    [0] => Array
        (
            [name] => 預約項目
            [column] => item_name
        )
    [1] => Array
        (
            [name] => 預約時間
            [column] => start_time
        )
    [2] => Array
        (
            [name] => 預約姓名
            [column] => full_name
        )
    [3] => Array
        (
            [name] => 報名人數1
            [column] => num_of_people
        )
    [4] => Array
        (
            [name] => 連絡電話
            [column] => phone
        )
    [5] => Array
        (
            [name] => 預約帳戶
            [column] => user_id
        )
    [6] => Array
        (
            [name] => 建立時間
            [column] => create_time
        )
)

通常,使用标量值:

$elements = array('foo', ...);
array_splice($array, $position, $length, $elements);

要在数组中插入一个数组元素,不要忘记将数组包装在数组中(因为它是一个标量值!):

$element = array('key1'=>'value1');
$elements = array($element);
array_splice($array, $position, $length, $elements);

否则,数组的所有键都将逐条添加。

在数组开头添加元素的提示:

$a = array('first', 'second');
$a[-1] = 'i am the new first element';

然后:

foreach($a as $aelem)
    echo $a . ' ';
//returns first, second, i am...

but:

for ($i = -1; $i < count($a)-1; $i++)
     echo $a . ' ';
//returns i am as 1st element
$result_array = array();
$array = array("Tim","John","Mark");
$new_element = "Bill";
$position = 1; 

for ($i=0; $i<count($array); $i++)
    {
      if ($i==$position)
       {
          $result_array[] = $new_element;
       }
       $result_array[] = $array[$i];
    }

print_r($result_array); 

// Result will Array([0] => "Tim",[1] => "Bill", [2] => "John",[1] => "Mark")