2017-05-10 60 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