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)
);