繁体   English   中英

PHP多维数组

[英]PHP Multi dimentional array

这是我的代码。 我不知道为什么它不起作用。 我试图用 php for 循环打印我的表格,但网站上没有显示任何内容。 没什么

这是我试图打印出来的二维数组。

 <!--Arrays of weapons-->
 <?php
 $weapons = array(
 array("M4A1",1,78906,"TUCKER, LISBETH","SPC"),
 array("M4A1",2,78915,"HATHAWAY, HANNAH","1LT"),
 array("M4A1",3,78933,"HARRIS, LEE","SFC"),
 array("M4A1",4,78934,"WELCH, BRAD","SSG"),
 array("M9",1,1167552,"BLAND, MARGARET","CPT"),
 array("M249",1,101032,"TYSON, MICHELLE","1SG"),
 array("M249",2,101038,"MEDINA, TOBIAS","SPC"),
 array("M240B",1,104104,"COSTA, JOSHUA","SSG"),
 array("M2A1",1,1863848,"GARCIA, RIGOBERTO","SSG"),
 array("MK-19",1,19369,"NEUPANE, KISHOR","SPC")
 );
 ?>

这是我试图用来打印的代码。

<!--Create the Weapons List Table-->
 <table border ="1">
 <tr>
  <th>Type</th>
  <th>Buttstock #</th>
  <th>Serial #</th>
  <th>Name</th>
  <th>Rank</th>
 </tr>
 <!--Put two-dimentinal arrays in the table-->
 <?php foreach ($row = 0; $row < 10, $row++) {?>
  <tr>
  <?php for ($col = 0; $col < 5, $col++) {?>
   <td><?php echo $weapons[$row][$col];?></td>
  <?php }?>
  </tr>
  <?php }?>
 </table>

你必须使用foreach作为foreach (array_expression as $value)

foreach 构造提供了一种简单的方法来迭代数组。 foreach 仅适用于数组和对象,当您尝试在具有不同数据类型的变量或未初始化的变量上使用它时会发出错误。

像:

<?php
$weapons = array(
 array("Type 1",1,78906,"Apple","R1"),
 array("Type 2",2,78915,"Javascript","R4"),
 array("Type 3",3,78933,"Red","R6"),
 array("Type 4",4,78934,"Circle","R1"),
 array("Type 5",1,1167552,"Fried rice","R4"),
);
?>

<table border ="1">
     <tr>
      <th>Type</th>
      <th>Buttstock #</th>
      <th>Serial #</th>
      <th>Name</th>
      <th>Rank</th>
     </tr>
     <!--Put two-dimentinal arrays in the table-->
     <?php foreach ($weapons as $weapon) {?>
      <tr>
          <?php foreach ( $weapon as $val ) {?>
           <td><?php echo $val;?></td>
          <?php }?>
      </tr>
      <?php }?>
</table>

这将导致:

在此处输入图片说明

文档: foreach

增强埃迪的答案,也使用foreach
请注意,您可以像这样直观地简化代码:

<!--Arrays of weapons-->
<?php
$weapons = array(
  array("Type 1",1,78906,"Apple","R1"),
  array("Type 2",2,78915,"Javascript","R4"),
  array("Type 3",3,78933,"Red","R6"),
  array("Type 4",4,78934,"Circle","R1"),
  array("Type 5",1,1167552,"Fried rice","R4"),
);
?>
<table border ="1">
 <tr>
  <th>Type</th>
  <th>Buttstock #</th>
  <th>Serial #</th>
  <th>Name</th>
  <th>Rank</th>
 </tr>
 <!--Put two-dimentinal arrays in the table-->
 <?php
  foreach ($weapons as $weapon) {
    echo '<tr>';
    foreach ( $weapon as $val ) {
        echo "<td>$val</td>";
    }
    echo '</tr>';
  } ?>
</table>

为什么使用这个解决方案?
因为 php 标签的多次打开和关闭会使代码难以阅读。

关于foreach文档: http : //php.net/manual/en/control-structures.foreach.php

希望它有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM