欧美一区二区三区,国内熟女精品熟女A片视频小说,日本av网,小鲜肉男男GAY做受XXX网站

php 二維數(shù)組 添加元素

周雨萌1年前5瀏覽0評論
PHP中的二維數(shù)組是一種特殊的數(shù)組,它包含多個數(shù)組,每個數(shù)組中又包含多個值。在使用二維數(shù)組的過程中,添加元素是非常常見的操作。下面我們就來了解一下PHP二維數(shù)組添加元素的方法。
添加元素到二維數(shù)組中,可以使用array_push()函數(shù)或者直接添加鍵值對的方式。
首先來看array_push()函數(shù),它可以將一個或多個元素添加到數(shù)組末尾,并返回修改后的數(shù)組長度。例如:
$students = array(
array("name"=>"張三","age"=>20,"score"=>80),
array("name"=>"李四","age"=>21,"score"=>90),
array("name"=>"王五","age"=>22,"score"=>85)
);
array_push($students,array("name"=>"趙六","age"=>23,"score"=>88));
print_r($students);

以上代碼中,我們將一個新的數(shù)組添加到$students數(shù)組末尾,然后通過print_r()函數(shù)輸出整個數(shù)組。我們可以看到,輸出結(jié)果已經(jīng)包含了添加的新元素:
Array
(
[0] => Array
(
[name] => 張三
[age] => 20
[score] => 80
)
[1] => Array
(
[name] => 李四
[age] => 21
[score] => 90
)
[2] => Array
(
[name] => 王五
[age] => 22
[score] => 85
)
[3] => Array
(
[name] => 趙六
[age] => 23
[score] => 88
)
)

接下來,我們來看一下直接添加鍵值對的方式:
$students = array(
array("name"=>"張三","age"=>20,"score"=>80),
array("name"=>"李四","age"=>21,"score"=>90),
array("name"=>"王五","age"=>22,"score"=>85)
);
$students[3]["name"] = "趙六";
$students[3]["age"] = 23;
$students[3]["score"] = 88;
print_r($students);

以上代碼中,我們直接給$students數(shù)組的第四個元素(下標(biāo)為3)添加了三個鍵值對,然后也是通過print_r()函數(shù)輸出整個數(shù)組,我們可以看到,輸出結(jié)果也已經(jīng)包含了新添加的元素:
Array
(
[0] => Array
(
[name] => 張三
[age] => 20
[score] => 80
)
[1] => Array
(
[name] => 李四
[age] => 21
[score] => 90
)
[2] => Array
(
[name] => 王五
[age] => 22
[score] => 85
)
[3] => Array
(
[name] => 趙六
[age] => 23
[score] => 88
)
)

總的來說,在PHP中向二維數(shù)組中添加元素是非常簡單的,只要注意數(shù)組的層級和元素的鍵名即可。