Re: [SMARTY] Looping through two arrays inside eachother

From: Date: Fri, 30 Aug 2002 07:55:58 +0000
Subject: Re: [SMARTY] Looping through two arrays inside eachother
References: 1  Groups: php.smarty.general 
Request: Send a blank email to php-smarty-general+get-5875@lists.php.net to get a copy of this message
On Fri, 30 Aug 2002 09:17:55 +0200 "Eskil Kvalnes" <eskil@uten.net> wrote: > Hi, > I've been having trouble figuring out how I should do this so it works. Been > at it for about two hours now with different > solutions trying to figure it out, and now I'm really stuck. > For the record, the computer this is being developed on is using debian, php > 4.2.1, apache 1.3.26, and smarty 2.2.0. > > Here's my PHP code: > <code> > $newsSql = "SELECT * FROM news ORDER BY newsId DESC LIMIT 5;"; > $newsResult = $db->query($newsSql); > > $newsData = array(); > $commentsData = array(); > while ($newsRow = $newsResult->fetchRow(DB_FETCHMODE_ASSOC)) { > $newsData[] = $newsRow; > > $commentsSql = 'SELECT count(*) AS commentsCount FROM comments WHERE > commentKey = '.$newsRow['newsId']; > $commentsResult = $db->query($commentsSql); > > while ($commentsRow = $commentsResult->fetchRow(DB_FETCHMODE_ASSOC)) { > $commentsData[] = $commentsRow['commentsCount']; > } > } // moved here to improve the speed of while() loop $_SMARTY->assign('newsData', $newsData); $_SMARTY->assign('commentsData', $commentsData); > </code> > > and this is what I use in my template file (stripped out some HTML to make > it smaller.): > <code> > {foreach item=newsRow from=$newsData} > {$newsRow.newsDate|date_format:"%H:%M:%S - %d/%m/%Y"}<br><br> > Comments ({foreach item=commentsRow > from=$commentsData}{$commentsRow.commentsCount}{/foreach})<br> > {/foreach} > </code> It seems that you want to loop through two arrays in parallel. I think that {section} is more usefull here: > <code> > {section name=j loop=$newsData} > {$newsData[j].newsDate|date_format:"%H:%M:%S - %d/%m/%Y"}<br><br> > Comments ({$commentsData[j].commentsCount})<br> > {/section} > </code> > This is where something goes wrong.. instead of printing out 'Comments (1)' > on the first newspost and Comments (0) on the following four (it lists five > newspost > but there's only one comment wich belongs to the first newspost, it prints > out 'Comments (10000)'... > > I've checked the manual on foreach, foreachelse and tried to use some of the > examples there but no luck. > > Any input would be appreciated. -- Sincerely yours, Grigory V. Kareev

« previous php.smarty.general (#5875) next »