$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>';
}
我有两个数组,我想在表格的不同列中显示它们。 $ ad显示完美,但我在第二列的$ inlcude中显示内容时遇到问题。我尝试过另一个foreach循环来迭代第二个数组的内容,但这实际上是通过将随机值放在表格的不同位置来搞砸我的表格。除了foreach循环之外,我不知道有任何其他方法来遍历数组。任何建议都将不胜感激。谢谢!
我希望图表看起来像$ p = $ post和$ i = $ in。此外,第一行中有三列,之后是每行中的两列
$p $p $p
$p $i
$p $i
答案 0 :(得分:1)
假设您的数组格式正确,您可能希望使用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)),这意味着你可以同时运行两个foreach()。唯一的区别是array_shift()具有破坏性。