2017-05-10 36 views
0

我知道这是使用smarty在html中显示数据的常见问题。今天早上我刚开始使用smarty,并且正在检查网络/这里还是/为了解决方案,但是3个小时后我放弃了。PHP Smarty数组到字符串

我有错误数组字符串转换,并没有其他想法做什么。我知道这是在论坛上,但我检查了他们。

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

+0

停止使用mysqli_ *函数,它们自php5.5弃用,并从php7.0中移除(防止迁移) – MTroy

+2

@Mroroy mysql_ *'函数已折旧,而不是'mysqli_ *'。 – FrankerZ

+0

为什么你给'rrows'分配一个字符串,然后用它作为'foreach'中的数组? –

回答

0

不能破灭,因为$ rrows是多维数组

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

选项1:

可以删除此

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

,只是传递数组到HTML

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

and you ma Ÿ尝试使用内爆在HTML 所以..它应该是这样的

{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); 
+0

好吧,明白了,如果ii想要在模板“number 1 number 2 number 3”中,没有逗号?我来到了上面我刚刚编辑的内容,但是这也给我编号906。 – widmopl

+0

在foreach中使用'if condition' – HeeMZa