Re: [SMARTY-GENERAL] Another Array-Loop-Question
| From: | Bertrand DUNOGIER | Date: | Tue, 09 Apr 2002 07:11:25 +0000 |
| Subject: | Re: [SMARTY-GENERAL] Another Array-Loop-Question | ||
| References: | 1 | Groups: | php.smarty.general |
| Request: | Send a blank email to php-smarty-general+get-3570@lists.php.net to get a copy of this message | ||
while ($db->>next_record()) {
JD> $CATS[$db->f('id')] = array ($db->f('name'),
JD> $db->f('indent') );
JD> }
JD> an other view is:
JD> $CATS [1005] [0] = Science Fiction
JD> $CATS [1005] [1] = 2
JD> $CATS [1006] [0] = Fantasy
JD> $CATS [1006] [1] = 2
Using non-consecutive array indexes in an array you assign to smarty
is not a good idea. You'd better use sthg like
while ($db->>next_record()) {
$CATS[] = array ($db->f('name'), $db->f('indent'),
$db->f('id'));
}
So that you get
$CATS [0] [0] = Science Fiction
$CATS [1] [1] = 2
$CATS [2] [0] = Fantasy
$CATS [3] [1] = 2
(if you need the ids, just add them to the data, like i did.
JD> How can I access this array in a template, so I get
JD> something like this:
Your array (the one with 1005 & 1006) can be accessed using foreach:
{foreach from=$CATS key=KEY item=CAT}
{$KEY} -> {$CAT.0} -> {$CAT.1}<br />
{/foreach}
With the solution i provided, you can use a section:
{section name=x loop=$CATS}
{$CATS[x].2} -> {$CATS[x].0} -> {$CATS[x].1}
{/section}
Oh, and associative arrays are much better with smarty...
while ($db->>next_record()) {
$cat['id'] = $db->f('id');
$cat['name'] = $db->f('name');
$cat['indent'] = $db->f('indent');
$CATS[] = $cat;
}
{section name=x loop=$CATS}
{$CATS[x].id} -> {$CATS[x].name} -> {$CATS[x].indent}
{/section}
Much easier to read.
Hope it helps,
Bertrand