【问题标题】:How to filter an array based on mutliple conditions PHPPHP如何根据多个条件过滤数组
【发布时间】:2021-06-13 14:39:36
【问题描述】:

我有以下数组,我想根据某些条件更改输出

   foreach($courses as $c) {
$c->type == "fulltime" ? 'full' : 'part';
                    $f = new stdClass();
                    $f->course_id = $c->course;
                    $f->form =  $c->id;
                    $f->module = $c->module;
                    $f->unread = $unreadcount;
                    $f->type = $c->type;
                    $f->posts = $posts;   
                
                 $results[$c->course_id][$c->type][] = $f;
    }

当前结构:

 [course_id]{
       full : [
                       $f->form =  $c->id;
                    $f->module = $c->module;
                    $f->type = $c->type; [ex: fulltime, parttime]
                  
            ]
    part : []
    posts : []
    }

条件:

if ($enableFulltimeCourse =1 && $unreadcount >0) -> 显示 full[] 和 part[] 否则为空 if ($enableParttimeCourse =1 && $f->type == "part") -> 显示部分[] 否则为空

我尝试了什么

if ($enableFulltimeCourse =1 && $unreadcount >0){
                    unset($f);
                }
                $results[$forum->course][$forum->type][] = $f;

请指教

【问题讨论】:

  • 你能解释一下吗
  • @Jerson $courses 数据包含全日制和非全日制课程的结果以及基于课程类型的未读项目。通过我的前端获取值,我需要根据这些条件准备数组。例如:$enableFulltimeCourse 有一个值,未读项目不是 0,那么我想显示全职项目和帖子的子数组。否则这些子数组应该为空。我根据条件尝试了 unset($f) 但它不起作用。
  • @NicoHaase if ($enableFulltimeCourse =1 && $unreadcount >0) { unset($f);} 我试过这样但它没有用。它为每个项目返回 null。
  • 你为什么要使用unset?为什么不使用array_filter

标签: php arrays filter


【解决方案1】:

您需要使用===== 进行比较。另外,不确定你的意思是 show X else it's empty,但这里是如何形成你的条件。我不认为您的意思是 unset($f); - 因为那会删除您的整个对象。

if ($enableFulltimeCourse == 1)
  if ($unreadcount >0){
    // show full[] and part[] else its empty
    foreach($f->full as $item) {
       // loop through the full
    }

    foreach($f->part as $item) {
       // loop through the part
    }
  } else if ($f->type == "part") {
    unset($f->full); //show part[] else its empty
    foreach($f->part as $item) {
       // loop through the part
    }
  }
}
$results[$forum->course][$forum->type][] = $f;

【讨论】:

  • @dilzdilz - - 这有助于解决您的问题吗?如果是这样,请接受作为答案。谢谢
猜你喜欢
  • 2018-10-04
  • 1970-01-01
  • 2021-01-27
  • 1970-01-01
  • 2021-01-03
  • 1970-01-01
  • 2020-08-16
  • 2021-04-21
相关资源
最近更新 更多