phparrayssmartysmarty3smarty2

Smarty assign and display two dimensional array


I want to get a two dimensional array's data and display it in a html file using smarty: The idea is as following: my array contains several arrays everyone contains the category name in the first offset and the attached links to this category

1-file php

$categories_links = array();//array that contains some catgories name with the attached links
//some dummy data
$categorie1="Horror movies";
$link11="http://www.movie11.com";
$link12="http://www.movie12.com";
$link13="http://www.movie13.com";
$categories_links[] = array($categorie1, $link11, $link12,$link13);
$categorie2="Action movies";
$link21="http://www.movie21.com";
$link22="http://www.movie22.com";
$categories_links[] = array($categorie2, $link21, $link22);
$smarty->assign('categories_links' , $categories_links );
$smarty->display('file.html');

2-file html

{foreach key=categorie item=categorie from=$categories_links}
    foreach key=categorie item=categorie from=categorie}
 <!--
  1.display only the first item in every array as the category name
  2.display the rest as the links attached to the above category

//-->
  {/foreach}
{/foreach}

Solution

  • I'd refactor the data array to use the category name as a key.

    $categories = array(
      'Horror movies' => array(
        'link1',
        'link2',
        /...
      ),
      'Action movies' => array(
        'link1',
        'link2',
        /...
      ),
    );
    $smarty->assign("categories", $categories);
    

    Then you can use it easily in Smarty

    {foreach from=$categories key=category item=links}
      Category: {$category}
      {foreach from=$links item=link}
      {$link}
      {/foreach}
    {/foreach}
    

    It is much easier to use that way.