微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 使用For循环打印表中的多维数组

我想使用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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐