Home >Backend Development >PHP Tutorial >Deep talk on php multidimensional arrays

Deep talk on php multidimensional arrays

PHP中文网
PHP中文网Original
2017-10-27 09:10:071120browse

The values ​​in one array can be another array, and the values ​​in another array can also be an array. In this way, we can create a two-dimensional or three-dimensional array:

Example

<?php
// 二维数组:
$cars = array
(
    array("Volvo",100,96),
    array("BMW",60,59),
    array("Toyota",110,100)
);
?>

PHP - Multidimensional Array

Multidimensional array is An array containing one or more arrays.

In a multi-dimensional array, each element in the main array can also be an array, and each element in the sub-array can also be an array.

In this example, we create a multidimensional array with automatically assigned ID keys:

<?php 
$sites = array 
( 
    "runoob"=>array 
    ( 
        "php中文网", 
        "http://www.php.cn" 
    ), 
    "google"=>array 
    ( 
        "Google 搜索", 
        "http://www.google.com" 
    ), 
    "taobao"=>array 
    ( 
        "淘宝", 
        "http://www.taobao.com" 
    ) 
); 
print("<pre class="brush:php;toolbar:false">"); // 格式化输出数组 
print_r($sites); 
print("
");  ?>

The above array will output the following:

Deep talk on php multidimensional arrays

Example 2

Let us try to display a value in the above array:

echo $sites ['runoob'][0] . 'The address is:' . $sites['runoob'][1];

Methods for multi-dimensional array traversal

$a=array(&#39;fruits&#39;=>array(&#39;a&#39;=>&#39;orange&#39;,&#39;b&#39;=>&#39;grape&#39;,c=>&#39;apple&#39;),
 &#39;numbers&#39;=>array(1,2,3,4,5,6),
 &#39;holes&#39;=>array(&#39;first&#39;,5=>&#39;second&#39;,&#39;third&#39;)
 );
//第一种:
foreach($a as $list=>$things){
 if(is_array($things)){
 foreach($things as $newlist=>$counter){
 echo "key:".$newlist."<br/>"."value:".$counter."<br/>";
 }
}
}
//第二种:
function MulitarraytoSingle($array){
   $temp=array();
   if(is_array($array)){
     foreach ($array as $key=>$value )
     {
       if(is_array($value)){
         MulitarraytoSingle($value);
       }
       else{
         $temp[]=$value;
       }
     }
   }
}


The above is the detailed content of Deep talk on php multidimensional arrays. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn