Search code examples
phphtmlsmarty

PHP Smarty Array to string


I know that's common problem with display data in html with smarty. I just started today this morning using smarty, and was checking net /here also/ for solution, but after 3 hours I gave up.

I have error Array to string conversion and have no other ideas what to do. I know that was on forum,but I checked them.

<?php
require_once('Smarty.class.php');
//include_once('project_config.php');

$link    = mysqli_connect("localhost", "test", "test", "tcg_test");
$smarty  = new Smarty();


$q = "SELECT person, id FROM person
      WHERE person.type_id = 
      (
          SELECT type_id FROM tcg_test.type 
          WHERE type_key = 'company.owner'
      )";

if($result = mysqli_query($link, $q))
{
    printf("Select returned %d rows.\n", mysqli_num_rows($result));
}

$rrows     = array();
while($row = mysqli_fetch_row($result))
{
     $rrows[] = $row;
}

$rows_string = implode( "," , $rrows);
$smarty->assign('rrows',$rows_string);

$smarty->display('compare.tpl');
mysqli_free_result($result);

?>

HTML

        {foreach $rrows as $row}
            {$row}
        {/foreach}

And $rrows

array(4) {
  [0]=>
  array(2) {
    [0]=>
    string(33) "number 1 ....."
    [1]=>
    string(3) "906"
  }
  [1]=>
  array(2) {
    [0]=>
    string(19) "number 2...."
    [1]=>
    string(3) "906"
  }
  [2]=>
  array(2) {
    [0]=>
    string(29) "number 3 ....."
    [1]=>
    string(3) "906"
  }
  [3]=>
  array(2) {
    [0]=>
    string(25) "number 4....."
    [1]=>
    string(3) "906"
  }
}

I came to this:

            {section name=record loop=$rrows}
                {foreach from=$rrows[record] item=entry key=name}

                    <option> {$entry} </option>
                 {/foreach}
            {/section}

but i dont need number 906


Solution

  • You cannot implode because $rrows is multi dimensional array

    $rows_string = implode( "," , $rrows);
    

    Option 1 :

    You may remove this

    $rows_string = implode( "," , $rrows);
    $smarty->assign('rrows',$rows_string);
    

    and just pass array to your html

    $smarty->assign('rrows',$rrows);
    

    and you may try using implode in your html So.. it should be something like this

    {foreach $rrows as $row}
        {{ ','|implode:$row }}
    {/foreach}
    

    Option 2 :

    If you not using $rrows somewhere else you may do implode in your while loop

    $rrows     = array();
    while($row = mysqli_fetch_row($result))
    {
         $rrows[] = $row;
    }
    
    $rows_string = implode( "," , $rrows);
    $smarty->assign('rrows',$rows_string);
    

    into something like this

    $rrows     = array();
    while($row = mysqli_fetch_row($result))
    {
         $rrows[] = implode( "," , $row);
    }
    
    $smarty->assign('rrows', $rrows);