PHP Smarty 数组转字符串

PHP Smarty Array to string

我知道这是在 html 中使用 smarty 显示数据的常见问题。我今天早上才开始使用 smarty,并且也在/这里/检查网络以寻求解决方案,但 3 小时后我放弃了。

我在数组到字符串的转换中遇到错误,不知道该怎么做。我知道那是在论坛上,但我查过了。

<?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}

还有$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"
  }
}

我来到这里:

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

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

但我不需要 906

你不能内爆,因为 $rrows 是多维数组

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

选项 1:

您可以删除此

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

然后将数组传递给您的 html

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

您可以尝试在 html 中使用 implode 所以..应该是这样的

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

选项 2:

如果您不在其他地方使用 $rrows,您可能会在 while 循环中内爆

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

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

变成这样

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

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