2017-07-26 64 views
-3

我想要一个具有20个名称的数组的foreach循环。我应该派生一个有4列和5行的表格,每个单元格(表格数据)都有一个唯一的名称。我的代码如下,输出表的快照。它还没有工作。我怎样才能解决这个问题?从foreach循环获取每个数组项目作为表数据

<?php 

$names = array("Patrick","Raymond","George","Hosea","Samuel","Alan","June","Edwin","Yvonne","John","Paul","Ruto","Uhuru","Raila","Kalonzo","Sonko","Joho","Wetangula","Mudavadi","Matiang'i"); 


echo "<table width='200' border='1' >"; 

foreach($names as $name){ 

echo "<tr>"; 

    for($cols=1;$cols<5;$cols++){ 

    echo "<td>".$name."</td>"; 

    } 

echo "<tr>"; 

} 

echo "<table>"; 

?> 

enter image description here

+0

是的,那是因为你这样做了发言..删除,只是限制了TD的每个TR代替每个数组项目回显5 td – ThisGuyHasTwoThumbs

回答

5

1:删除for

第二:申请使用$i

注1极限:您的循环single name 5倍。那不应该。

注2:欲了解更多详情,请阅读我的评论专栏。

<?php 

$names = array("Patrick","Raymond","George","Hosea","Samuel","Alan","June","Edwin","Yvonne","John","Paul","Ruto","Uhuru","Raila","Kalonzo","Sonko","Joho","Wetangula","Mudavadi","Matiang'i"); 


echo "<table width='200' border='1' >"; 

$i=0; 
foreach($names as $name){ 

if($i==0){ //open new tr if $i is 0 
echo "<tr>"; 
} 
    echo "<td>".$name."</td>"; 

if($i==3){ //close the tr if the $i is reached the 3 . 

echo "</tr>"; 

$i=-1; //why setting -1 means i'm incrementing after this so i set -1 
} 

$i++; 
} 

echo "<table>"; 

?> 
+0

非常感谢。现在让我想出这个:) –

+0

很高兴帮助你:) – JYoThI

2

拆分数组到所需大小的块可作出更可读的代码:

$names = array("Patrick","Raymond","George","Hosea","Samuel","Alan","June","Edwin","Yvonne","John","Paul","Ruto","Uhuru","Raila","Kalonzo","Sonko","Joho","Wetangula","Mudavadi","Matiang'i"); 

echo "<table width='200' border='1' >"; 

$names = array_chunk($names, 4); 

foreach($names as $group){ 
    echo "<tr>"; 
    foreach($group as $name) { 
     echo "<td>".$name."</td>"; 
    } 
    echo "</tr>"; 
} 

echo "<table>";