Note that there are some explanatory texts on larger screens.

plurals
  1. POForeach in a while loop
    text
    copied!<p>I’ve two tables: “cars” and “dealerships”:</p> <p><strong>Cars table</strong></p> <pre><code>id_car | name_car | etc. ---------------------------- 1 | A3 Sportback | etc. 2 | Ranger | etc. 3 | Transit Van |etc. 4 | Cayman | etc. etc. | etc. | etc. </code></pre> <p><strong>Dealerships table</strong></p> <p>In deal_cars column I insert ids of correspondent cars as array.</p> <pre><code>deal_id | deal_name | deal_cars | etc. -------------------------------------- 1 | Ford | 2,3 | etc. 2 | Audi | 1 | etc. 3 | Porsche | 4 | etc. etc. | etc. | etc. | </code></pre> <p>I’d get a page that displays the following information: </p> <p><strong>Dealership name – Cars</strong></p> <ul> <li>Ford – Ranger, Transit Van</li> <li>Audi – A3 Sportback</li> <li>Cayman – Porsche</li> </ul> <p>I’ve no problem to extract the dealership name, but I don’t know how to extract the car names from ids. </p> <p>I tried this:</p> <pre><code>$dealerships_sql = $data-&gt;query("SELECT * FROM dealerships ORDER BY deal_name ASC"); while($dealerships_obj = $data-&gt;extract($dealerships_sql)){ //Dealerships data $deal_id[] = $dealerships_obj-&gt;deal_id; $deal_name[] = $dealerships_obj-&gt;deal_name; etc etc //Try to get cars ids and turn them in cars names. $deal_cars[] = $dealerships_obj-&gt;deal_cars; $deal_cars[] = explode(',',$deal_cars); $cars = array(); foreach ($deal_cars AS $deal_car) { $cars_sql = $data-&gt;query("SELECT name_car FROM cars WHERE id_car = '$deal_car'"); while($cars_obj = $data-&gt;extract($cars_sql)){ $cars[] = stripslashes($cars_obj-&gt;name_car)." "; } } } </code></pre> <p>I use smarty as template engine so I assign some vars:</p> <pre><code>$smarty-&gt;assign ("deal_id", $deal_id); $smarty-&gt;assign ("deal_name", $deal_name); etc etc. $smarty-&gt;assign ("cars", $cars); </code></pre> <p>And my template is:</p> <pre><code>&lt;table border="1"&gt; &lt;tr&gt; &lt;td&gt;Dealership&lt;/td&gt; &lt;td&gt;Cars&lt;/td&gt; &lt;/tr&gt; {section name="foo" loop=$deal_name} &lt;tr&gt; &lt;td&gt;{$deal_name[foo]}&lt;/td&gt; &lt;td&gt;{$cars[foo]}&lt;/td&gt; &lt;/tr&gt; {/section} &lt;/table&gt; </code></pre> <p>But code returns:</p> <ul> <li>Ford – Ranger</li> <li>Audi – A3 Sportback</li> <li>Cayman – Porsche</li> </ul> <p>It shows only the first car (first element found in array) for each dealership. How can I solve this?</p>
 

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