Find a single element in a Smarty array [solved]

Have a question or a suggestion about a 3rd party addon module or plugin?
Let us know here.
Post Reply
billandsonia
Forum Members
Forum Members
Posts: 13
Joined: Mon Apr 21, 2008 5:40 pm

Find a single element in a Smarty array [solved]

Post by billandsonia »

In the Add/Edit an Event form, the CGCalendar module loops over the $categories array like this:

Code: Select all

{foreach from=$categories item='category'}
<div class="row">
  <p class="row_prompt">{$category->name}:</p>
  <p class="row_input">
    {$category->field}
  </p>
</div>
{/foreach}
I am trying to work with just one of the category names - I want to be able to access each category name directly, without a loop, and to understand how to access that. I've tried the following (and at least the same number of other variations) with no success (no output). I don't think the first element is null or blank, because the array above throws out 'General' as the first result.

Code: Select all

{$categories->name.0}
{$categories->name[0]}
{$categories.0->name}
{$categories[0]->name}
{$categories->name}
{$categories[$name.0]}
{$categories[$name].0}
{$categories.0.$name}
{$categories.name.0}
I need to stop bashing my head against the wall now... all of the documentation is good at explaining how to loop over an array, not how to access an individual element.
Last edited by billandsonia on Sun Nov 13, 2011 8:54 pm, edited 1 time in total.
spcherub
Power Poster
Power Poster
Posts: 402
Joined: Fri Jun 06, 2008 5:54 pm

Re: Find a single element in a Smarty array

Post by spcherub »

This works:

Code: Select all

{$categories[1]->name}
For some reason the $categories array is not zero-based. So if you have three categories defined, their names can be accessed as follow:

Code: Select all

{$categories[1]->name}
{$categories[2]->name}
{$categories[3]->name}
The best way to figure this out for other variables is to use a print_r smarty modifier, so something like this (below) will tell you exactly how the variable is structured:

Code: Select all

<pre>{$categories|@print_r}</pre>
Hope that helps.

-S
billandsonia
Forum Members
Forum Members
Posts: 13
Joined: Mon Apr 21, 2008 5:40 pm

Re: Find a single element in a Smarty array [solved]

Post by billandsonia »

Thanks, spcherub!

Two lessons I needed to be reminded of:

1) Double-check the obvious

2) Don't assume
Post Reply

Return to “Modules/Add-Ons”