首页 > 解决方案 > 从 foreach 中删除整个数组

问题描述

我正在尝试过滤和删除与特定值匹配的数组。我从 API 获取 JSON,然后通过 PHP 使用 json_decode 对其进行解码。它显示得非常好,但它提出了我不想要的值。

JSON 文件 = https://pastebin.com/raw/7yW1CEdu

我正在使用以下 foreach 语句,它可以工作并显示我需要的每个统计数据的数据(为了专注于删除数组,我已经剥离了它):

<?php foreach($json['response']['data'] as $item) { 
      
    $newarray = array_filter($item['competitionName'], function($var) {
        return ($var != 'Junior SS Premiership Zone 3');
    });
  }
?>

这就是我希望它与当前外观相比的外观 - https://gyazo.com/d8654cc939dba9e0e52f06e66f489323

我的 array_filter 代码有什么问题?我希望它删除任何明确声明的数组: "competitionName":"Junior SS Premiership Zone 3"因此该数组中的任何数据都不会在 foreach 中处理。

谢谢!

标签: phpjsonforeach

解决方案


$item['competitionName']是一个字符串,而不是字符串数组。我想你想要的是:

$data = array_filter($json['response']['data'], function ($item) {
    return $item['competitionName'] != 'Junior SS Premiership Zone 3';
});
foreach ($data as $item) {
    // display the data
}

或者不要打扰过滤器,只需在主循环中检查它并跳过它。

foreach ($json['response']['data'] as $item) {
    if ($item['competitionName'] == 'Junior SS Premiership Zone 3') {
        continue;
    }
    // process the item
}

推荐阅读