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


当前回答

$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")

其他回答

你可能会觉得这更直观一些。它只需要调用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。

你可以试试,用这个方法让它变得简单

/**
 * 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
        )
)

这样你就可以插入数组:

function array_insert(&$array, $value, $index)
{
    return $array = array_merge(array_splice($array, max(0, $index - 1)), array($value), $array);
}
$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")

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

$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