简体   繁体   English

在smarty中,如何检查关联数组是否为空?

[英]In smarty, how to check whether an associative array is empty or not?

I done google for it, but couldn't get the correct solution. 我为谷歌做了,但无法得到正确的解决方案。 Can any one help me out to check whether the associative array is empty or not. 任何人都可以帮我检查关联数组是否为空。 Thanks in Advance. 提前致谢。

In Smarty3, you can use PHP's empty() function : 在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}

Outputs Array is empty . 输出Array is empty

It seems that Smarty just check if array exists. 似乎Smarty只检查数组是否存在。 For example 例如

somefile.php

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

template.tpl

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

Outputs Array is set . 输出Array is set

While in php... 在php中...

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

outputs Array is not set . 输出Array is not set

To solve this, i made a little workaround: created a modifier for smarty with the following code: modifier.is_empty.php 为了解决这个问题,我做了一点解决方法:使用以下代码为smarty创建了一个修饰符: modifier.is_empty.php

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

Save that snippet in your SMARTY_DIR , inside the plugins directory with name modifier.is_empty.php and you can use it like this: 将该片段保存在SMARTY_DIR ,名称为modifier.is_empty.phpplugins目录中,您可以像这样使用它:

template.tpl ( considering using the same somefile.php ) template.tpl (考虑使用相同的somefile.php

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

This will output Array is empty . 这将输出Array is empty

A note about using this modifier agains using @count modifier: 有关使用@count修饰符@count使用此修饰符的说明:
@count will count the amount of elements inside an array, while this modifier will only tell if it is empty, so this option is better performance-wise @count将计算数组中元素的数量,而此修饰符仅指示它是否为空,因此此选项在性能方面更好

You can put the variable directly in an if-statement as long as you're sure it'll be always set (empty or not) like so {if !$array} . 您可以将变量直接放在if语句中,只要您确定它将始终设置(空或不),就像{if !$array} If you're looking for something akin to a ternary operator you could use variable modifier called default eg. 如果您正在寻找类似于三元运算符的东西,则可以使用名为default的变量修饰符。 $array|default:"empty" . $array|default:"empty" There's also some help in smarty docs and on their forum . 在smarty docs和他们的论坛上也有一些帮助。 Using PHP's empty also worked for me. 使用PHP为空也对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM