我用谷歌搜索了一下,但找不到正确的解决方案。谁能帮我检查一下关联数组是否为空?提前谢谢。
发布于 2014-03-18 17:54:00
在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。
发布于 2014-01-13 04:31:24
似乎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);
}
?>将该代码片段保存在plugins目录下的SMARTY_DIR中,名称为modifier.is_empty.php,您可以这样使用它:
template.tpl (考虑使用相同的somefile.php )
{if !($array|is_empty)}
Array is not empty
{else}
Array is empty
{/if}这将输出Array is empty。
有关再次使用此修饰符的说明,请使用@count修饰符:
@count将计算数组中元素的数量,而此修饰符只会告诉您它是否为空,因此此选项在性能方面更好
发布于 2013-04-13 19:37:45
您可以将变量直接放在if语句中,只要您确定它将始终被设置(空或不是),就像这样设置{if !$array}。如果你正在寻找类似于三元运算符的东西,你可以使用名为default的变量修饰符,例如。$array|default:"empty"。在他们的forum上也有一些帮助in smarty docs。使用PHP的empty对我也很有效。
https://stackoverflow.com/questions/15987319
复制相似问题