PHP数组多维
2018-02-22 16:40 更新
PHP教程 - PHP数组多维
多维数组可以有数组作为其值。
包含其他数组的数组是二维数组。如果这些数组也包含数组,那么顶层数组是一个三维数组,依此类推。
以下代码使用数组运算符([])创建二维阵列。 第一级的关键是Java和PHP。
<?PHP
$book["Java"] = array("Name"=>"Java Book", "Price"=> 1.2, "OnSale"=>"No");
$book["PHP"] = array("Name"=>"PHP Book", "Price"=>5.3, "OnSale"=>"Yes");
var_dump($book);
?>
上面的代码生成以下结果。
示例 - 使用array()函数创建二维数组
以下脚本创建一个称为的简单二维数组$ myBooks,然后使用print_r()显示其内容。
<?php /* ww w .j a va2 s. co m*/
$myBooks = array(
array(
"title" => "Learn PHP from www.w3cschool.cn",
"author" => "www.w3cschool.cn",
"pubYear" => 2000
),
array(
"title" => "Learn Java from www.w3cschool.cn",
"author" => "JavaAuthor",
"pubYear" => 2001
),
array(
"title" => "Learn HTML from www.w3cschool.cn",
"author" => "HTMLAuthor",
"pubYear" => 2002
),
array(
"title" => "Learn CSS from www.w3cschool.cn",
"author" => "CSSAuthor",
"pubYear" => 2003
),
);
print_r ( $myBooks );
?>
上面的代码生成以下结果。
多维数组中的PHP访问元素
方括号语法可以访问a中的任何元素多维数组。
访问第一个维度
$multidimensionalArray[]
访问内部尺寸
$multidimensionalArray[][]
这里有些例子
<?php /*from w ww . j ava2 s . c o m*/
$myBooks = array(
array(
"title" => "Learn PHP from www.w3cschool.cn",
"author" => "www.w3cschool.cn",
"pubYear" => 2000
),
array(
"title" => "Learn Java from www.w3cschool.cn",
"author" => "JavaAuthor",
"pubYear" => 2001
),
array(
"title" => "Learn HTML from www.w3cschool.cn",
"author" => "HTMLAuthor",
"pubYear" => 2002
),
array(
"title" => "Learn CSS from www.w3cschool.cn",
"author" => "CSSAuthor",
"pubYear" => 2003
),
);
print_r( $myBooks[1] );
echo $myBooks[1]["title"] . "\n";
echo $myBooks[3]["pubYear"] . "\n";
?>
上面的代码生成以下结果。
PHP循环通过多维数组
多维数组基本上是嵌套在其他数组内的数组,我们可以使用嵌套循环通过多维数组!
我们可以使用以下嵌套的foreach语句循环通过多维数组。
foreach ( $myBooks as $book ) { foreach ( $book as $key => $value ) { } }
以下示例使用两个嵌套的foreach循环循环遍历$ myBooks数组。
<?php /* w w w. java2s . c o m*/
$myBooks = array(
array(
"title" => "Learn PHP from www.w3cschool.cn",
"author" => "www.w3cschool.cn",
"pubYear" => 2000
),
array(
"title" => "Learn Java from www.w3cschool.cn",
"author" => "JavaAuthor",
"pubYear" => 2001
),
array(
"title" => "Learn HTML from www.w3cschool.cn",
"author" => "HTMLAuthor",
"pubYear" => 2002
),
array(
"title" => "Learn CSS from www.w3cschool.cn",
"author" => "CSSAuthor",
"pubYear" => 2003
),
);
$bookNum = 0;
foreach ( $myBooks as $book ) {
$bookNum++;
echo "Book #$bookNum:";
foreach ( $book as $key => $value ) {
echo "$key :$value \n";
}
}
?>
上面的代码生成以下结果。
以上内容是否对您有帮助:
更多建议: