2013-04-13 24 views
1

我做了谷歌它,但無法得到正確的解決方案。任何人都可以幫助我檢查關聯數組是否爲空。提前致謝。在smarty中,如何檢查一個關聯數組是否爲空?

+1

對不起,但我很難相信你把「聰明的數組空」在谷歌,並找不到答案?嘗試一些關於第一個結果的提示,比如'!$ array'或'$ array | @count == 0',這取決於你的數組是否可以是空的或數組,然後你想檢查以及.. – Nanne

回答

3

在Smarty3,你可以使用PHP's empty() function

somefile.php

<?PHP 
$smarty->assign('array',array()); 
$smarty->display('template.tpl'); 

template.tpl

{if empty($array)} 
    Array is empty 
{else} 
    Array is not not empty 
{/if} 

輸出Array is empty

0

只要你確定它總是被設置(空或不),就可以直接把變量放在if語句中,就像{if !$array}一樣。如果你正在尋找類似於三元運算符的東西,那麼可以使用名爲default的變量修飾符。 $array|default:"empty"。還有一些幫助in smarty docs和他們的forum。使用PHP的空也爲我工作。

1

看來Smarty只是檢查數組是否存在。例如

somefile.php

<?PHP 
$smarty->assign('array',array()); 
$smarty->display('template.tpl'); 

template.tpl

{if $array} 
    Array is set 
{else} 
    Array is not set 
{/if} 

輸出Array is set。在PHP

雖然...

<?PHP 
$array = array(); 
if($array){ 
    echo 'Array is set'; 
}else{ 
    echo 'Array is not set'; 
} 

輸出Array is not set

爲了解決這個問題,我做了一點變通方法:創建一個修改爲智者用下面的代碼: modifier.is_empty.php

<?PHP 
function smarty_modifier_is_empty($input) 
{ 
    return empty($input); 
} 
?> 

保存在您的SMARTY_DIR片斷中,plugins目錄裏面的名字modifier.is_empty.php,你可以使用這樣的:

template.tpl

(使用相同的 somefile.php考慮) 0

這將輸出Array is empty

有關使用使用@count修改此修改agains的說明:
@count會計算一個數組中的元素的量,而這個修改只會告訴我們,如果它是空的,所以這個選項是更好的性能明智