PHP多维数组

时间:2018-03-31 05:57:40

标签: php html arrays for-loop

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

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

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

Dim valCheck As Variant

For i = 0 To row1
    For j = 0 To col1
        MsgBox ("started" & i)
        valCheck = Range("A1").Offset(i, j).Value
        MsgBox (valCheck)
        If valCheck = "Details" Then
            MsgBox ("found")
            ActiveCell = Range("A1").Offset(i + 1, j)
            Exit For
            Exit For
        End If
    Next j
Next i

2 个答案:

答案 0 :(得分:2)

您必须使用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>

这将导致:

enter image description here

Doc:foreach

答案 1 :(得分:1)

使用foreach增强Eddie的答案,
请注意,您可以直观地简化代码:

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

希望它有所帮助。