[Solved] filtering json data in php laravel


You can json_decode that json string and then use array_filter method to filter regions

$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];

12

solved filtering json data in php laravel