PHP Show foreach() 结果来自 2 个 SQLite-array,其中一个是随机的


PHP Show foreach() results from 2 SQLite-arrays, one as random

我有 2 个 SQLite- 表,一个包含文章,一个包含图像 URL。我想做的是做一个foreach()来按顺序显示文章,并在文章旁边显示一定数量的随机图像。

应通过检查文章和图像类别(表中的列)之间的相似性来选择图像,然后随机化。(例如,文章类别可以是"摩托艇"和img类别"船")。

如何显示两个不同数组的结果?文章的代码是:

    $stmt = $db->prepare('SELECT * FROM Article WHERE category = "article" ORDER BY pubdate DESC;');
$stmt->execute();
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<div id="artikelLista">
  <?php foreach($res as $article): ?>
  <div class="artikelContent">
 <?php echo $article['title']; ?><br>
<?php echo $article['content'];?>
    <div class="floatRight clear"><?php echo "Artikel skriven " . $article['author'] . " " . $article['pubdate']; ?></div>
  </div>
  <?php endforeach; ?>

要添加第二个数组,我尝试了这个,但没有用,它只多次显示第一个数组的结果:

$stmt = $db->prepare('SELECT * FROM Article WHERE category = "article" ORDER BY pubdate DESC;');
$stmt->execute();
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt2 = $db->prepare('SELECT * FROM Object;');
$stmt2->execute();
$res2 = $stmt2->fetchAll(PDO::FETCH_ASSOC);
?>
<div id="artikelLista">
  <?php foreach($res as $article): ?>
<?php foreach($res2 as $object): ?>
  <div class="artikelContent">
 <?php echo $article['title']; ?><br>
<?php echo $article['content'];?><br>
<?php echo $object['img'];?> <!-- For testing. The images should be filtered and a a few random images would be shown here -->
    <div class="floatRight clear"><?php echo "Artikel skriven " . $article['author'] . " " . $article['pubdate']; ?></div>
  </div>
  <?php endforeach; ?>
  <?php endforeach; ?>

我想不可能像这样使用嵌套的foreach()。我将如何管理它?

另外,如果有人知道如何匹配上述数组之间的相似之处,我会很棒。如果没有,我稍后会处理这个问题。

您可以将文章的第一个类别中的函数传递给该函数。现在在该函数中收集数组中的所有图像到传递的类别,然后通过随机化将其返回。下面的代码..

<?php foreach($res as $article): ?>
    <?php
    $img = get_img($article['category']);
    ?>
    <div class="artikelContent">
        <?php echo $article['title']; ?><br>
        <?php echo $article['content'];?><br>
        <img src="<?php echo $img; ?>" /> <!-- The return result will be shown here -->
        <div class="floatRight clear"><?php echo "Artikel skriven " . $article['author'] . " " . $article['pubdate']; ?></div>
    </div>
<?php endforeach; ?>
<?php
function get_img($category){

    $stmt2 = $db->prepare('SELECT * FROM Object WHERE category = '.$category);
    $stmt2->execute();
    $res2 = $stmt2->fetchAll(PDO::FETCH_ASSOC);
    $rnd = array();
    foreach($res2 as $object){
        $rnd[] = $object['img'];
    }
    $n = rand(0,(count($rnd)-1));
    return $rnd[$n];
}

?>