阅读量:9
array_push() 函数用于将一个或多个元素添加到数组的末尾。在多维数组中,可以使用array_push()函数将元素添加到多维数组的子数组中。
例如,考虑以下多维数组:
$students = array( array("name" => "John", "age" => 20), array("name" => "Jane", "age" => 22), array("name" => "Mike", "age" => 21) );
如果想要向特定学生的数组中添加额外的信息,可以使用array_push()函数:
array_push($students[0], "major" => "Computer Science");
这将在第一个学生的数组中添加一个新键值对 “major” => “Computer Science”。此时,$students数组将变为:
$students = array( array("name" => "John", "age" => 20, "major" => "Computer Science"), array("name" => "Jane", "age" => 22), array("name" => "Mike", "age" => 21) );
array_push()函数还可以一次向多维数组中的多个子数组添加元素。例如,可以向所有学生的数组中添加一个 “gpa” 键值对:
foreach ($students as $key => $student) { array_push($students[$key], "gpa" => 3.5); }
这将为每个学生的数组添加一个 “gpa” 键值对,$students数组将变为:
$students = array( array("name" => "John", "age" => 20, "major" => "Computer Science", "gpa" => 3.5), array("name" => "Jane", "age" => 22, "gpa" => 3.5), array("name" => "Mike", "age" => 21, "gpa" => 3.5) );