duanpanhuo0618 2016-12-08 11:49
浏览 219
已采纳

PHP适用于foreach循环结果中的条件

I don't have much knowledge in PHP, your help appreciated.

I created a database query and foreach loop in PHP for getting data from database, Here is my foreach code:

if($user->id != 0)
{
    foreach ( $results as $result) {
        $leftday = $result->dayleft;
        $subsexp   = "-";

        if( strpos( $leftday, $subsexp ) !== false ) {
            echo "Subscription Expired<br>";
        } else {
            echo "Subscription Active<br>";
        }
    }

}

Here the result as expected:

  • Subscription Expired
  • Subscription Expired
  • Subscription Active
  • Subscription Active

But how can I show only one "Subscription Expired" text when there are no any "Subscription Active"? Now it's showing 4 times "Subscription Expired" text when all subscription expired.

  • 写回答

2条回答 默认 最新

  • doulu3865 2016-12-08 12:05
    关注

    If what you mean is

    "When all subscriptions are expired show the message only once" then use an array to store the results (active / expired). Once you have all results stored you can process the array (if all expired do this, else do that). If you echo the resutls right away as you do now, without storing the results, you cannot act upon them, something like:

    <?php
    
    $results = [];
    $results['active'] = 0;
    $results['expired'] = 0;
    if($user->id != 0)
    {
        foreach ( $results as $result) {
            $leftday = $result->dayleft;
            $subsexp   = "-";
    
            if( strpos( $leftday, $subsexp ) !== false ) {
                $results['expired']++;
            } else {
                $results['active']++;
            }
        }
    
    }    //all expired
    if(0 == $results['active']){
        //do something
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色