PHP foreach +继续不处理多维数组

时间:2017-01-16 22:39:49

标签: php foreach

我正在寻找一种基于两个参数在foreach循环上过滤数组的方法..

我在输出中有以下数组:

[
  {
    "entry_id": "1",
    "title": "something",
    "grades": [
      "3",
      "4",
      "5",
      "6"
    ],
    "subject": [
      "science"
    ]
  },
  {
    "entry_id": "2",
    "title": "something else",
    "grades": [
      "7",
      "8",
      "9",
      "10"
    ],
    "subject": [
      "math"
    ]
  },
]

我正在尝试仅使用foreach + break返回entry_id 2,从我所看到的内容看起来似乎应该有效..

$subject = 'math';
$grade = '10';

foreach ( $results as $key => &$result ) {
        if($subject && !in_array($subject, $result['subject'])){
            break;
        }
        if($grade && !in_array($grade, $result['grades'])){
            break;
        }
}

但是它正在返回所有条目..

2 个答案:

答案 0 :(得分:0)

在通过任何测试时,您似乎需要将当前条目添加到新数组中。因此,将!in_array()测试更改为in_array(),然后在if块内添加结果。

$realresults = array();
foreach ( $results as $key => &$result ) {
    if($subject && in_array($subject, $result['subject'])){
        $realresults[] = $result;
    } elseif($grade && in_array($grade, $result['grades'])){
        $realresults[] = $result;
    }
}

答案 1 :(得分:0)

搜索后,似乎未设置+ array_values将执行我需要的操作:

foreach ( $results as $key => &$result ) {
    if($subject && !in_array($subject, $result['subject'])){
        unset($results[$key]);
        $results = array_values($results);
    }
    if($grade && !in_array($grade, $result['grades'])){
        unset($results[$key]);
        $results = array_values($results);
    }
}