php - 使用 For 循环在表中打印多维数组

标签 php for-loop multidimensional-array

<分区>

我只想使用 For 循环在表中打印多维数组。 这是$myArray

$myArray =    Array(
[0] => Array
    (
        [0] => 598
        [1] => Introducing abc
        [2] => 
    )
[1] => Array
    (
        [0] => 596
        [1] => Big Things Happening at abc
        [2] => 
    )
[2] => Array
    (
        [0] => 595
        [1] => Should I send abc?
        [2] => 
    )
[3] => Array
    (
        [0] => 586
        [1] => Things you need to know about abc :P
       [2] => 
    )  

);

将新数组更新为 var_dump($myArray );

最佳答案

有很多不同的方法可以解决这个问题,所以为什么不尝试一下呢。

如果你必须使用 for 循环

不知道你为什么会这样,除非是为了学校作业:

for($i=0;$i<count($data);$i++) {
  echo('<tr>');
  echo('<td>' . $data[$i][0] . '</td>');
  echo('<td>' . $data[$i][1] . '</td>');
  echo('<td>' . $data[$i][2] . '</td>');
  echo('</tr>');
}

但是直接访问 ID 有点愚蠢,让我们在行中使用另一个 for 循环:

for($i=0;$i<count($data);$i++) {
  echo('<tr>');
  for($j=0;$j<count($data[$i]);$j++) {
    echo('<td>' . $data[$i][$j] . '</td>');
  } 
  echo('</tr>');
}

将其替换为同样无聊的 foreach 循环:

<table>
<?php foreach($items as $row) {
  echo('<tr>');
  foreach($row as $cell) {
    echo('<td>' . $cell . '</td>');
  }
  echo('</tr>');
} ?>
</table>

为什么不内爆数组:

<table>
<?php foreach($items as $row) {
  echo('<tr>');
  echo('<td>');
  echo(implode('</td><td>', $row);
  echo('</td>');
  echo('</tr>');
} ?>
</table>

混成一团,拧紧foreach,走走走走;并在此过程中内爆:

<?php
function print_row(&$item) {
  echo('<tr>');
  echo('<td>');
  echo(implode('</td><td>', $item);
  echo('</td>');
  echo('</tr>');
}
?>

<table>
  <?php array_walk($data, 'print_row');?>
</table>

双走...我的天啊

是的,现在看起来有点傻,但是当你扩大表格并且事情变得更复杂时,事情会更好地分解和模块化:

<?php
function print_row(&$item) {
  echo('<tr>');
  array_walk($item, 'print_cell');
  echo('</tr>');
}

function print_cell(&$item) {
  echo('<td>');
  echo($item);
  echo('</td>');
}
?>

<table>
  <?php array_walk($data, 'print_row');?>
</table>

关于php - 使用 For 循环在表中打印多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16141590/

相关文章:

c - 为什么我的小 C 循环不能正确打印到帧缓冲区,但它的展开版本可以?

c++ - 为什么我的函数中的这个 for 循环只会运行一次,即使它应该运行多次?

php - 在php中的关联多维数组中插入键值对

python - 想要知道有多少对象位于两个不同子集的重叠部分

php - 滚动条出现在我的网站内

javascript - 如何检查浏览器是否支持公钥凭据?

javascript - 尝试使用 ErrorDocument 处理请求时遇到 500 Internal Server Error 错误

arrays - C中的指针数组,易于迭代

excel - 如何在 Excel 单元格 block 中查找非空的第一列并返回相应的列标题

php - 用其他数组中的值填充数组中的空值