Mảng hai chiều


Để truy cập đến các giá trị của phần tử mảng hai chiều, bạn có thể phát biểu vòng lập for, duyệt trên hàng và cột của mảng.

Ví dụ: duyệt phần tử mảng
Multidimential array<br>
<?php
 $products=array(array("TIR","Tires", 100),array("COR","Concord", 1000),array("BOE","Boeing", 5000));
 for ($row=0;$row<3;$row++)
   {
     for ($col=0;$col<3;$col++)
     {
   echo "\t|\t".$products[$row][$col];
  }
     echo "<br>";
   }
 $products[0][0]="A";
 $products[0][1]="A1";
 $products[0][2]=10;
 $products[1][0]="B";
 $products[1][1]="B1";
 $products[1][2]=20;
 $products[2][0]="C";
 $products[2][1]="C1";
 $products[2][2]=30;
 for ($row=0;$row<3;$row++)
   {
     for ($col=0;$col<3;$col++)
     {
   echo "\t|\t".$products[$row][$col];
  }
     echo "<br>";
   }
?>
</body>
</html>
Tuy nhiên, trong trường hợp bạn muốn in cột dữ liệu với tên cột, bạn có thể khai báo chúng như ví dụ dưới đây:
<html><body>
Multidimential array
<br>
<?php
 $products=array(array(Code=>"TIR",Description=>"Tires", Price=>100),array(Code=>"COR",Description=>"Concord", Price=>1000),array(Code=>"BOE",Description=>"Boeing", Price=>5000));
 for ($row=0;$row<3;$row++)
   {
      echo $products[$row]["Code"]."\t|\t".$products[$row]["Description"]."\t|\t".$products[$row]["Price"]."\t|\t";
     echo "<br>";
   }

?>
</body>
</html>
Cũng giống như trong trường hợp mảng một chiều, trong trường hợp mảng hai chiều bạn có thể sử dụng hàm list và hàm each cùng với phát biểu while để tách giá trị của mỗi hàng vào biến:
ví dụ:
<html><body>
Multidimential array
<br>
<?php
 $products=array(array(Code=>"TIR",Description=>"Tires", Price=>100),array(Code=>"COR",Description=>"Concord", Price=>1000),array(Code=>"BOE",Description=>"Boeing", Price=>5000));
 for ($row=0;$row<3;$row++)
   {
  while (list($key,$value)=each($products[$row]))
       echo "|$value";
     echo "<br>";
   }

?>
</body>
</html>


0 nhận xét to "Mảng hai chiều"

Đăng nhận xét