简体   繁体   中英

filtering json data in php laravel

I've a sample json data

"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}

             ]
            
      }
]

How can I filter out the data the based on id in the regions ? For example, if id is 2, then the response should be like

"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}

             ]
            
      }
 ]

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

First apply json_decode on your json data then apply filter . If you want to get an whole object from this response array , then write a function which will accept the id and return that object after filtering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM