Skip to content
Advertisement

PHP display while loop data accurately in SMARTY template

In the following code when I try to assign $viewAd value to the template file and display result it does not display the accurate results when assigned to the template. However, it displays the accurate desired result on top of the page when I straight echo the $viewAd in the PHP page. I have given the screenshots below.

My PHP Structure goes like this:

JavaScript

Screenshot 1 : Correct Result with straight PHP echo displays each category with ads in it

enter image description here

Screenshot 2 : Incorrect Result when variable assigned to the template displays only the last category with the ads in it

enter image description here

Why am I not getting the same result when I assign the variable to the template? I have also tried the array method where I declared $viewAds = array() before the while loop and later I assigned $viewAds[] = $viewAd. Then in the tpl file I tried to echo the value using foreach loop like this {foreach $viewAds as $vas}{$vas}{/foreach} but that still didn’t display each category and ads (the desired result like in the first screenshot). Since, it did not work using array as well I removed it and tried to echo {$viewAds} straight way and with foreach too. No luck, nothing is working. All gives the result as in second screenshot. Displaying only the last category with ad in it. However, since direct echo in PHP file is giving the correct result I am sure that my PHP logic is correct. It’s just that I am not being able to assign that result in the template file correctly and display it. What is the error I am making here? Am I missing out on something?

Advertisement

Answer

You need to initialize $viewAd before starting the first loop, something like:

JavaScript

Then each category should be appended to $viewAd :

JavaScript

This way all categories will be included in your final HTML.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement