仅当值不为空时才打印字段

时间:2016-10-25 13:02:54

标签: php

我有一个foreach语句,用于打印某些字段的标签和值:

<?php 
   foreach ($this->item->dpfields as $field) {
      echo '<li><b>'.$field->label.'</b>: '.$field->value.'</li>';
   }
?>

我想只打印非空的字段(标签和值)。

我该如何编辑此代码?

4 个答案:

答案 0 :(得分:1)

<?php 
    foreach ($this->item->dpfields as $field) {
        if (!empty($field->label) && !empty($field->value)) {
             echo '<li><b>'.$field->label.'</b>: '.$field->value.'</li>';
        }
    }
?>

根据注释编辑如何避免空列表并根据元素数设置类:

<?php 
    $itemCnt = count($this->item->dpfields);
    if ($itemCnt > 0) { 
        /* 
         * If there are more than one items in the list set col-md-6 and col-lg-6, 
         * otherwise set col-md-12 and col-lg-12 
         * (col-xs-12 and col-sm-12 are the same for both)
         */
        $liClass = ($itemCnt>1) ? 'col-xs-12 col-sm-12 col-md-6 col-lg-6' : 'col-xs-12 col-sm-12 col-md-12 col-lg-12';
        echo '<ul class="projectdetails">'; 
        foreach ($this->item->dpfields as $field) { 
            if (!empty($field->value)) { 
                echo '<li class="' . $liClass . '"><b>'.$field->label.'</b>: '.$field->value.'</li>'; 
            } 
        } 
        echo '</ul>'; 
    } 
?>

答案 1 :(得分:1)

试试这个

<?php 
  foreach ($this->item->dpfields as $field) {
    if($field->label!="" && $field->value!="") 
    {
       echo '<li><b>'.$field->label.'</b>: '.$field->value.'</li>';
    }
  }
?>

答案 2 :(得分:1)

如果定义$field,则此工作:

<?php 
    if (count($this->item->dpfields) > 0) {
        foreach ($this->item->dpfields as $field) {
            if (!empty($field->label) && !empty($field->value) {
                echo '<li><b>'.$field->label.'</b>: '.$field->value.'</li>'; 
            } 
        }
    } else {
        echo '<p>No results</p>';
    }

?>

您还可以使用:if (!empty($this->item->dpfields))。它是一样的。

empty()http://php.net/manual/en/function.empty.php

以下内容被认为是空的:

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)

答案 3 :(得分:1)

<?php 
    foreach ($this->item->dpfields as $field) {
      if(!empty($field->label) && !empty($field->value){
        echo '<li><b>'.$field->label.'</b>: '.$field->value.'</li>';
      }
    }
?>

试试这个:)