Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to loop two array with smarty?
    primarykey
    data
    text
    <p>I'm trying to make a simple forum script, based on smarty. </p> <p>On the front page I want to be able to display every category, and the forums linked to those categories. </p> <p>For this I have two tables on my database, "forums" and "forums_categories".</p> <pre> Forums table: +----+---------+-------------+ | id | value | category_id | +----+---------+-------------+ | 1 | Forum 1 | 1 | | 2 | Forum 2 | 2 | | 3 | Forum 3 | 1 | | 4 | Forum 4 | 2 | +----+---------+-------------+ forum_categories table: +----+------------+ | id | value | +----+------------+ | 1 | Category 1 | | 2 | Category 2 | +----+------------+ </pre> <p>This is my PHP code</p> <pre><code> $sql = "SELECT * FROM `forums_categories` ORDER BY `id` ASC"; $result = mysql_query($sql); if (mysql_num_rows($result) &gt; 0) { $category = array(); while ($row = mysql_fetch_assoc($result)) { $cat_id = $row['id']; $category[] = $row; # Get forums $sql2 = "SELECT * FROM `forums` WHERE category_id='$cat_id'"; $result2 = mysql_query($sql2); $forums = array(); while ($row2 = mysql_fetch_assoc($result2)) { $forums[] = $row2; } } } $smarty-&gt;assign('category', $category); $smarty-&gt;assign('forums', $forums); </code></pre> <p>This is what I have on my forum.tpl file.</p> <pre><code> {section name=i loop=$category} &lt;li&gt;{$category[i].id} - {$category[i].value}&lt;/li&gt; {section name=o loop=$forums} &lt;li&gt;{$forums[o].category_id} - {$forums[o].value}&lt;/li&gt; {/section} {/section} </code></pre> <p>I want to get this:</p> <p>1 - Category 1<br/> 1 - Forum 1<br/> 1 - Forum 3<br/></p> <p>2 - Category 2<br/> 2 - Forum 2<br/> 2 - Forum 4<br/></p> <p>but instead I'm getting this:</p> <p>1 - Category 1<br/> 2 - Forum 2<br/> 2 - Forum 4<br/></p> <p>2 - Category 2<br/> 2 - Forum 2<br/> 2 - Forum 4<br/></p> <p>(Notice how on Category 1 I'm getting the forums with category_id 2 instead of 1)</p> <p>What's wrong with my code? If anyone can help point me in the right direction I would be most thankful.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload