繁体   English   中英

在同一表中显示两个数组

[英]Display two arrays in the same table

$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 

假设您的数组格式正确,则可能要使用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()具有破坏性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM