Search code examples
phparrayssmartysmarty3smarty2

Grabbing certain values from an array in Smarty


I have been trying this for hours, If it was just PHP I would be done by now but this requires Smarty 3 so things are a little different. I am having difficulty grabbing specific keys plural from an Array. The Array looks like this

Array
(
    [0] => Array
        (
            [id] => 1
            [client] => Jane Doe
            [email] => [email protected]
        )
   [1] => Array
        (
            [id] => 2
            [client] => John Doe
            [email] => [email protected]
        )
   [2] => Array
        (
            [id] => 3
            [client] => Jim Doe
            [email] => [email protected]
        )

I can access this using PHP just fine, the Smarty is tripping me up, the files are two

  • clients.php
  • clients.tpl <- smarty

I assign the array in the .php file with the following

$totalEntries = $results['products']['product'];
$ca->assign('innerArray', $totalEntries);

The $results['products']['product'] is what outputs the array seen above.

Now in the .tpl file, I have the following

  <select class="form-control" id="sel1">
   {foreach $innerArray as $results} 
    {foreach from=$results.client item=label}
    <option value="{$label}">{$label}</option>
    {/foreach}
  {/foreach}
  </select>

This works to output to the dropdown

  • Jane Doe
  • John Doe
  • Jim Doe

I got that part right, and I have been looking all over the internet to figure this out. My plan was to introduce into the drop down something like

However when I attempt this using something like the following where i remove the .client part of the from=

  <select class="form-control" id="sel1">
   {foreach $innerArray as $results} 
    {foreach from=$results item=label}
    <option value="{$label.client}">{$label.client} - {$label.email}</option>
    {/foreach}
  {/foreach}
  </select>

I am met with a list that looks like this

  • 1 - 1
  • J - J
  • j - j
  • 2 - 2
  • J - J
  • j - j
  • 3 - 3
  • J - J
  • j - j

I realize this is basically the first letters and numbers, but I see variety of examples online showing that I can take from the array what I need, but when I try $label.client - $label.email It won't work.

What am I doing wrong?


Solution

  • It's not like the way you did, but using {section} will do:

    <select class="form-control" id="sel1">
    {section name=seq loop=$innerArray}
      <option value="{$innerArray[seq].id}">{$innerArray[seq].client} - $innerArray[seq].email}</option>
    {/section}
    </select>