技术笔记
PHP 阵列(数组)合并、增加元素、插入指定位置
 moons   2020-07-27 17:17:08   131
专栏分类: PHP

开头插入用:array_unshift
$num = array(10, 45, 9);
array_unshift($num, 100, 6);  //在数组开头插入元素
print_r($num);


1.合并 note: call by value.

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)

2.增加 note: call by reference.

<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)

3.插入指定位置 note: call by reference.

<?php
$array1 = array('a', 'b', 'c', 'd', 'e');
$array2 = array('x');
array_splice($array1, 3, 0, $array2); // 插入到位置3且删除0个
print_r($array1);
?>
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => x
    [4] => d
    [5] => e
)
Copyright © mos360.cn By Moons Soft Studio 百度统计