【问题标题】:filtering json data in php laravel在php laravel中过滤json数据
【发布时间】:2021-09-25 03:09:54
【问题描述】:

我有一个示例 json 数据

"regions": [
      {
            "id": 1,
            "name": "Region 1",
            "state_id": 1,
            "areas" :[ {
                   "id": 1,
                   "name": "area 1",
                   "region_id": 1},
                     {
                   "id": 2,
                   "name": "area 2",
                   "region_id": 1}

             ]
            
      },
      {
            "id": 2,
            "name": "Region 2",
            "state_id": 1,
            "areas" :[ {
                   "id": 3,
                   "name": "area 3",
                   "region_id": 2},
                     {
                   "id": 4,
                   "name": "area 4",
                   "region_id": 2}

             ]
            
      }
]

如何过滤掉regions中基于id的数据?例如,如果id 是 2,那么响应应该是这样的

"regions": [
 {
            "id": 2,
            "name": "Region 2",
            "state_id": 1,
            "areas" :[ {
                   "id": 3,
                   "name": "area 3",
                   "region_id": 2},
                     {
                   "id": 4,
                   "name": "area 4",
                   "region_id": 2}

             ]
            
      }
 ]

【问题讨论】:

  • regions json 来自数据库还是其他数据源?
  • 你不能通过json_decode() 解析它并执行array_filter() 吗?
  • 其他数据源。 @MohsenNazari

标签: php json laravel


【解决方案1】:

你可以json_decode那个json字符串,然后用array_filter方法过滤区域

$regions = json_decode('{"regions": 
[
  {
    "id": 1,
    "name": "Region 1",
    "state_id": 1,
    "areas" :[ {
      "id": 1,
      "name": "area 1",
      "region_id": 1
    },{
      "id": 2,
      "name": "area 2",
      "region_id": 1
    }]
  },{
    "id": 2,
    "name": "Region 2",
    "state_id": 1,
    "areas" :[{
      "id": 3,
      "name": "area 3",
      "region_id": 2
    },{
      "id": 4,
      "name": "area 4",
      "region_id": 2
    }]
  }
]
}', true);

// Filter Region
$region_id = 2;
$filtered_regions = array_filter($regions['regions'], function($r) use ($region_id) {
  return $r['id'] == $region_id;
});

// Filter By Area Id
$area_id = 2;
$filtered_areas = array_filter($regions['regions'], function($r) use ($area_id) {
  $areas = array_filter($r['areas'], function($area) use ($area_id) {
    return $area['id'] == $area_id;
  });

  return count($areas) > 0;
});

return ['regions' => $filtered_regions];

【讨论】:

  • 我认为我应该使用$r->id 而不是 $r['id']
  • 你是对的,如果json_decode中的第二个参数没有设置为true,那么它将解码为对象。
  • 如果我想过滤掉区域,我应该使用$r->areas->id 吗?
  • 不,由于$r->areas 是数组,您可以循环遍历它并找到正确的ID,或者通过索引获取特定区域。 $r->areas[0]->id
  • 我建议循环浏览一下
【解决方案2】:

首先在您的 json 数据上应用 json_decode 然后应用 filter 。如果你想从这个响应数组中获取一个完整的对象,那么编写一个函数来接受 id 并在过滤后返回该对象。

【讨论】:

  • 与接受的答案相同的答案,重复
猜你喜欢
  • 2021-12-23
  • 1970-01-01
  • 2016-05-24
  • 2018-01-24
  • 2020-08-29
  • 1970-01-01
  • 2023-03-25
  • 2021-12-03
  • 1970-01-01
相关资源
最近更新 更多