2017-07-26 15 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

第一:

第二forループを削除します。$i

注1使用制限を適用します。あなたは.thatはいけない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>"; 
関連する問題