$row = $query->fetchAll(PDO::FETCH_ASSOC);
$num_rows = count($row);
for ($i = 0; $i < $num_rows; $i++)
{
$title = htmlspecialchars($row[$i]['title']);
$author =htmlspecialchars($row[$i]['author']);
$school =htmlspecialchars($row[$i]['school']);
$solution = $row[$i]['solution'];
$notes = $row[$i]['notes'];
$ad = array($title, $price, $author, $school, $contact, $content, $date);
$inlcude = array($solutions, $notes);
$field = 0;
echo "<table border='1'>";
// foreach($inlcude as $in) This failled miserably
foreach ($ad as $post)
{
if ($field < 3) //The first three values are placed in the first row
{
echo "<td>$post</td>";
}
if ($field >= 3)
{
echo "<tr><td>$post</td><td>$in</td></tr>";
}
$field++;
}
echo '</table>';
}
2つの配列があり、テーブルの異なる列に表示したいと思います。$ adは完全に正常に表示されますが、2番目の列の$ inlcudeの内容を表示するのに問題があります。2番目の配列の内容を反復処理するために別のforeachループを配置しようとしましたが、テーブルのさまざまな場所にランダムな値を配置することで、テーブルが実際に台無しになります。foreachループ以外に、配列を反復処理する他の方法はわかりません。任意の提案をいただければ幸いです。ありがとう!
$ p = $ postと$ i = $ inのグラフを次のようにしたいと思います。さらに、最初の行に3列、その後のすべての行に2列
$p $p $p
$p $i
$p $i
配列が正しくフォーマットされていると仮定すると、おそらくarray_shift()を使用する必要があります。次のようなものを試してください。
// Start by copying the $include array, because array_shift() is a destructive
// operation and you might want to use $includes again.
$includes_copy = $include;
// Start with your leading <tr> cell.
echo "<tr>";
// Now loop your ad array.
foreach ($ad as $post) {
//The first three values are placed in the first row.
if ($field < 3) {
echo "<td>$post</td>";
$field++;
}
if ($field == 3) {
echo "</tr>"; // Closing tags are good form.
}
if ($field >= 3) {
// Using array_shift() will return the first element from the array.
// The returned element will be removed from the array.
$in = array_shift($includes_copy);
// $post is populated from foreach(), $in is populated by array_shift().
echo "<tr><td>$post</td><td>$in</td><td></td></tr>";
$field += 3;
}
}
基本的に、foreach($ array as $ val)はwhile($ val = array_shift($ array))と論理的に同等であるという概念です。つまり、2つのforeach()を同時に実行できます。唯一の違いは、array_shift()が破壊的であることです。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加