从foreach循环获取每个数组项作为表数据

时间:2017-07-26 10:16:57

标签: php loops

我在20个名字的数组上尝试foreach循环。我应该派生一个包含4列和5行的表,每个单元格(表数据)都有一个唯一的名称。我的代码在下面,带有输出表的快照。它还没有奏效。我该如何解决这个问题?

<?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

2 个答案:

答案 0 :(得分:5)

1st:删除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>";

?>

答案 1 :(得分: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>";