PHP多维数组

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (78)

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

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

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

<!--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>
提问于
用户回答回答于

你必须使用foreachasforeach (array_expression as $value)

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

喜欢:

<?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")
);
?>

<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>

这将导致:

Doc:foreach

用户回答回答于

加强埃迪的答案,用foreach为好, 注意,你可以直观地简化了这样的代码:

<!--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")
);
?>
<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

希望能帮助到你。

扫码关注云+社区

领取腾讯云代金券