Muh*_*zad 3 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] =>
)
Run Code Online (Sandbox Code Playgroud)
);
将新数组更新为 var_dump($myArray );
due*_*lsy 26
这有很多不同的方法,所以为什么不用它来玩.
不知道为什么你会这样做,除非是为了学校作业:
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>');
}
Run Code Online (Sandbox Code Playgroud)
但是那个有点愚蠢的直接访问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>');
}
Run Code Online (Sandbox Code Playgroud)
<table>
<?php foreach($items as $row) {
echo('<tr>');
foreach($row as $cell) {
echo('<td>' . $cell . '</td>');
}
echo('</tr>');
} ?>
</table>
Run Code Online (Sandbox Code Playgroud)
<table>
<?php foreach($items as $row) {
echo('<tr>');
echo('<td>');
echo(implode('</td><td>', $row);
echo('</td>');
echo('</tr>');
} ?>
</table>
Run Code Online (Sandbox Code Playgroud)
<?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>
Run Code Online (Sandbox Code Playgroud)
是的,它现在看起来有点傻了,但是当你长大桌面并且事情变得更复杂时,事情会更好地分解和模块化:
<?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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34991 次 |
| 最近记录: |