2

我从我的模型中获取一组数据,并使用 php foreach 语句将其显示在视图中。我正在添加另一层逻辑以仅显示某些书签 ID。

数据显示正常;但由于某种原因,“else”消息(与第一个 if 子句相关)没有显示是否没有返回数据。我需要弄清楚如何显示该消息。

<?php 

     if ($bookmark): 
     foreach($bookmark as $b): ?>               

     <?php if ($b->bookmark_id != 0) { ?>               

     <li><?php echo $bk->user_id; ?> <?php echo $bk->bookmark_name; ?></li>

     <?php } ?>


     <?php
      endforeach;
        else:
          print "Your bookmark list is empty.";
    endif;

?>
4

3 回答 3

6

你测试 $bookmark 是否存在!我假设它总是存在的,要么是空的,要么是值数组!

尝试这个:

<?php 

if (is_array($bookmark) && count($bookmark)>=1): 
  foreach($bookmark as $b): ?>               

  <?php if ($b->bookmark_id != 0) { ?>               

    <li><?php echo $bk->bookmark_name; ?></li>

  <?php } ?>


  <?php
  endforeach;
else:
  print "Your bookmark list is empty.";
endif;

?>

阅读:PHP is_array() | 数数()

已编辑

与最近发表的评论相关 “是的,数组正在返回结果;我正在使用第二个 if 语句来限制显示的内容。听起来我的 else 语句应该与第二个 if 子句而不是第一个子句相关联。问题对我来说,不是有没有结果,而是过滤后的结果有没有残留。”

<?php 

// reset variable
$count = 0;

// if it is an array and is not empty
if (is_array($bookmark) && count($bookmark)>=1): 
  foreach($bookmark as $b):
    if ($b->bookmark_id != 0) {               
      echo '<li>' . $bk->bookmark_name . '</li>';
    } else {
      $count++; // no data, increase
    }

    // check if the counter was increased 
    if ($count>=1) {
      print "Your bookmark list is empty.";
    }
  endforeach;
else:
  print "bookmark not found.";
endif;

?>
于 2012-05-12T23:55:15.153 回答
0

For one reason or another, $bookmark is evaluating to true. Since empty strings and arrays already evaluate to false in PHP, we might reasonably suppose that $bookmark is in fact an object. Since we can iterate over it with foreach, it is probably an instance of ArrayObject, or a class that extends it. We could debug the exact type of $bookmark by writing:

var_dump($bookmark);

Since an empty object instance evaluates to true in a PHP conditional, we need to be more specific about what we're checking for.

if(count($bookmark) > 0):

This should trigger the else condition properly. As a side note, you should really indent your code properly. :)

于 2012-05-12T23:59:14.917 回答
0
if (is_array($bookmark) && !empty($bookmark)) { 
  foreach ($bookmark as $item) {               
   ...
  }
} else {
  echo "Your bookmark list is empty.";
}
于 2014-08-29T11:52:17.823 回答