lundi 29 décembre 2014

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

I have 2 SQLite- tables, one containing articles and one containing image URL's. What I'd like to do is to do a foreach() to show the articles in order and show a set number of random images next to the article.


The images should be selected by checking similarity between the Article's and image's categories (column in the table) and then randomized. (The article catergory could be for example 'motorboats' and the img category 'boat').


How do I show the results from two different arrays? The code for the articles is:



$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; ?>


To add the second array, I tried this, which didn't work, it only showed the results from the first array multiple times:



$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; ?>


I guess it's not possible to use nested foreach() like this. How will I manage this?


Also, If anyone knows on top of their head how to match the similarities between the arrays as described above, I'd be greatful. If not, I'll deal with this later.


Aucun commentaire:

Enregistrer un commentaire