Search code examples
phparrayssmarty

how to display array values in table smarty php


I have array:

$kraje = Array(
      array('Polska', 'Anglia', 'Litwa', 'Francja'),
      array('Tunezja', 'Egipt', 'RPA', 'Etiopia'),
      array('Chiny', 'Mongolia', 'Japonia', 'Kazachstan')
);

I would like to display this in html table in smarty index.tpl or just in php. the result I want:

http://codepen.io/anon/pen/LxJpaV

<table style="">
  <tr>
    <th>array1</th>
    <th>array2</th> 
    <th>array3</th>
  </tr>
  <tr>
    <td>Polska</td>
    <td>Tunezja</td> 
    <td>Chiny</td>
  </tr>
  <tr>
    <td>Anglia</td>
    <td>Egipt</td> 
    <td>Mongolia</td>
  </tr>
  <tr>
    <td>Litwa</td>
    <td>RPA</td> 
    <td>Japonia</td>
  </tr>  
  <tr>
    <td>Francja</td>
    <td>Etiopia</td> 
    <td>Kazachstan</td>
  </tr>   
</table>

Solution

  • index.php:

    require("vendor/autoload.php");
    $smarty = new Smarty();
    
    $kraje = Array(
          array('Polska', 'Anglia', 'Litwa', 'Francja'),
          array('Tunezja', 'Egipt', 'RPA', 'Etiopia'),
          array('Chiny', 'Mongolia', 'Japonia', 'Kazachstan')
    );
    $i = new MultipleIterator();
    foreach ($kraje as $a) $i->attachIterator (new ArrayIterator ($a));
    
    $smarty->assign('name', $i);
    $smarty->display("sample.tpl");
    

    sample.tpl:

    <table style="">
      <tr>
        <th>array1</th>
        <th>array2</th> 
        <th>array3</th>
      </tr>
      {foreach $name as $item}
      <tr>
         {foreach $item as $record}
         <td>{$record}</td>
         {/foreach}
      </tr>
      {/foreach}
    </table>