溫馨提示×

array_push在多維數(shù)組中的應(yīng)用

小樊
88
2024-06-26 17:14:56
欄目: 編程語言

array_push() 函數(shù)用于將一個或多個元素添加到數(shù)組的末尾。在多維數(shù)組中,可以使用array_push()函數(shù)將元素添加到多維數(shù)組的子數(shù)組中。

例如,考慮以下多維數(shù)組:

$students = array(
    array("name" => "John", "age" => 20),
    array("name" => "Jane", "age" => 22),
    array("name" => "Mike", "age" => 21)
);

如果想要向特定學(xué)生的數(shù)組中添加額外的信息,可以使用array_push()函數(shù):

array_push($students[0], "major" => "Computer Science");

這將在第一個學(xué)生的數(shù)組中添加一個新鍵值對 “major” => “Computer Science”。此時,$students數(shù)組將變?yōu)椋?/p>

$students = array(
    array("name" => "John", "age" => 20, "major" => "Computer Science"),
    array("name" => "Jane", "age" => 22),
    array("name" => "Mike", "age" => 21)
);

array_push()函數(shù)還可以一次向多維數(shù)組中的多個子數(shù)組添加元素。例如,可以向所有學(xué)生的數(shù)組中添加一個 “gpa” 鍵值對:

foreach ($students as $key => $student) {
    array_push($students[$key], "gpa" => 3.5);
}

這將為每個學(xué)生的數(shù)組添加一個 “gpa” 鍵值對,$students數(shù)組將變?yōu)椋?/p>

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

0