php数组前端表现 array_chunk妙用
php:
<?php $conn=mysql_connect("localhost","admin","1123581321"); mysql_query("set names utf8"); mysql_select_db("mytest"); $result=mysql_query("SELECT * FROM `mm`"); while ($arry=mysql_fetch_assoc($result )){ $menu[]=$arry; } echo "<pre>"; print_r($menu); echo "</pre>"; ?>
Array ( [0] => Array ( [ID] => 1 [name] => 前端 [parent_ID] => 0 ) [1] => Array ( [ID] => 2 [name] => php [parent_ID] => 0 ) [2] => Array ( [ID] => 3 [name] => javascript [parent_ID] => 1 ) )
遇到这种情况,一般在前端的表现是循环<ul>内部使用<li>浮动实现,但假如我要实现[parent_ID]处换行呢,有的会使用限制收缩父级元素限制li元素宽度一点一点的调整,或者clear等等,虽然效果没有问题,但是在标签结构和以后的灵活性上都会有很大的影响。
最好的方法当然是table,有人说table的css控制上有影响,一派胡言。关键是将二维数组转变为三维
<?php foreach ($menu as $d){ $f[]=array_chunk($d, 2); } ?>
结果
Array ( [0] => Array ( [0] => Array ( [0] => 1 [1] => 前端 ) [1] => Array ( [0] => 0 ) ) [1] => Array ( [0] => Array ( [0] => 2 [1] => php ) [1] => Array ( [0] => 0 ) ) [2] => Array ( [0] => Array ( [0] => 3 [1] => javascript ) [1] => Array ( [0] => 1 ) ) )
这样的话用table就完全没有问题了。、
<?php foreach ($f as $d){?> <table> <?php foreach ($d as $tr){?> <tr> <?php foreach ($tr as $td){?> <td><?php echo $td?></td> <?php }?> </tr> <?php }?> </table> <?php }?>
最后想说即使是CSS3,HTML5都普及了<table>也是必不可少的。