how to print an array in smarty?

16,910

Solution 1

You don't have to use {foreach} if you just want to print one associative array. Just use $array.key format.

In this case, you should print the name by using:

{$team_record.name}

If you have multiple associative arrays. You can use:

{foreach from=$team_record key=team item=record}
    {$record.name}
{/foreach}

Solution 2

we can Use {$team_record|print_r} to dsiplay whole Array in the smarty file.

Output:

 Array
 (
    [id] => 1                  
    [name] => doge_finder
    [total_rewards] => 52.00524500
    [desciption] => team is only of doge miners
    [created_by] => 20
)

we can Use below Code to iterate the Array in Smarty file

{foreach from=$team_record key=arrayIndex item=trecord}
   {$arrayIndex}: {$trecord}
   <br>
{/foreach}

Output :

       id: 1

       name: doge_finder

       total_rewards: 52.00524500

       desciption: team is only of doge miners

       created_by: 20 
Share:
16,910
codeBYmahesh
Author by

codeBYmahesh

&lt;?php echo "CODER"; ?&gt;

Updated on July 12, 2022

Comments

  • codeBYmahesh
    codeBYmahesh almost 2 years

    I have an array:

     $team_details = Array ( [id] => 1 [name] => doge_finder [total_rewards] => 52.00524500 [desciption] => team is only of doge miners [created_by] => 20 );
    
    /* assigning to a smarty template */
    $smarty->assign("team_record", $team_details);          
    $smarty->display($tpl);
    

    In template file:

    {foreach from= $team_record key=team item=trecord}
    {$trecord[$key].name}
    {/foreach}
    

    In result output must be "doge_finder", but I got first initial character of each record in array ie. "1 d 5 t 2"

    how can I resolve this problem?

  • codeBYmahesh
    codeBYmahesh about 10 years
    thank you, it's working fine. Because of I have an associative array that's why I wrote {foreach} to print that array.
  • codeBYmahesh
    codeBYmahesh about 10 years
    if there multidimensional array like: Array ( [0] => Array ( [id] => 1 [name] => doge_finder [total_rewards] => 52.00524500 [desciption] => team is only of doge miners [created_by] => 20 [created_date] => ) [1] => Array ( [id] => 2 [name] => Late Miner [total_rewards] => 45.25462000 [desciption] => Team player are late coin miners [created_by] => 20 [created_date] => ) ) then may I know how can it possible to print only name field in this array?