[英]In smarty, how to check whether an associative array is empty or not?
我為谷歌做了,但無法得到正確的解決方案。 任何人都可以幫我檢查關聯數組是否為空。 提前致謝。
在Smarty3中,您可以使用PHP的empty()函數 :
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
。
似乎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
。
為了解決這個問題,我做了一點解決方法:使用以下代碼為smarty創建了一個修飾符: modifier.is_empty.php
<?PHP
function smarty_modifier_is_empty($input)
{
return empty($input);
}
?>
將該片段保存在SMARTY_DIR
,名稱為modifier.is_empty.php
的plugins
目錄中,您可以像這樣使用它:
template.tpl
(考慮使用相同的somefile.php
)
{if !($array|is_empty)}
Array is not empty
{else}
Array is empty
{/if}
這將輸出Array is empty
。
有關使用@count
修飾符@count
使用此修飾符的說明:
@count
將計算數組中元素的數量,而此修飾符僅指示它是否為空,因此此選項在性能方面更好
您可以將變量直接放在if語句中,只要您確定它將始終設置(空或不),就像{if !$array}
。 如果您正在尋找類似於三元運算符的東西,則可以使用名為default的變量修飾符。 $array|default:"empty"
。 在smarty docs和他們的論壇上也有一些幫助。 使用PHP為空也對我有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.