Filter JSON Data in PHP
- Dipankar Sarkar
- March 22, 2023
- Backend
Question:
Answer:
<?php
$json = ‘ [{ “name”: “Necklace”, “created_at”: “2019-03-01” }, { “name”: “Bracelet”, “created_at”: “2019-03-05” }, { “name”: “Dog Chain”, “created_at”: “2020-05-27” }] ‘;
function myfilter($json, $startDate, $endDate) {
$array = json_decode($json,true);
$new = array();
$startDate = ‘2019-03-01’;
$endDate = ‘2019-03-31’;
foreach($array as $value) {
foreach($value as $key => $val) {
if($key == ‘created_at’) {
if($val >= $startDate && $val <= $endDate) {
$new[] = $value;
}
}
}
}
$new_json = json_encode($new,true);
return $new_json;
}
echo myfilter($json, ‘2019-03-01’, ‘2019-03-31’);
?>