方法一:使用array_push()函数
array_push()函数用于将一个或多个元素添加到数组的末尾。该函数返回更新后数组的新长度。
语法:
array_push(array, value1, value2, ...)
其中,array表示需要添加元素的数组;value1, value2, ...表示需要添加到数组中的元素。
示例:
<?php$students = array('tom', 'john', 'peter');array_push($students, 'lucy', 'james');print_r($students);?>
输出结果:
array( [0] => tom [1] => john [2] => peter [3] => lucy [4] => james)
方法二:使用“+”运算符
在php中,可以使用“+”运算符将两个数组合并到一个新数组中。如果两个数组中存在相同的键名,则第二个数组中的元素将覆盖第一个数组中的元素。
语法:
$array = $array1 + $array2;
其中,$array1和$array2是要合并的两个数组。
示例:
<?php$students1 = array('tom', 'john', 'peter');$students2 = array('lucy', 'james');$students = $students1 + $students2;print_r($students);?>
输出结果:
array( [0] => tom [1] => john [2] => peter [3] => lucy [4] => james)
方法三:直接赋值
在php中,可以直接将一个元素赋值给一个新数组的一个指定键名。如果该键名已经存在,则覆盖该键名对应的元素。
示例:
<?php$students = array();$students['english'] = 'tom';$students['math'] = 'john';$students['science'] = 'peter';print_r($students);?>
输出结果:
array( [english] => tom [math] => john [science] => peter)
以上就是php中将数据添加到新数组中的三种方法。根据实际需求选择合适的方法,可以更加高效地操作数组。
以上就是php中怎么将数据添加到新数组的详细内容。