I have a set json data. In that i have to return a json with key and value pair in php. I used the json as follows
[{
"id": "1995",
"name": "Banahatti"
},
{
"id": "5074",
"name": "Kolhapur(Maharashtra)"
},
{
"id": "2356",
"name": "Bmbur"
},
{
"id": "906",
"name": "Ammla"
},
{
"id": "536",
"name": "Puttur"
},
{
"id": "1308",
"name": "Poogolam"
},
{
"id": "1217",
"name": "Sarangpur"
},
{
"id": "826",
"name": "Hiriyur"
},
{
"id": "24911",
"name": "Himmatnagar"
},
{
"id": "3993",
"name": "Podili"
}]
In this json values , i have to search and get json ,if i give a name value is starting with B
means i have to get result json as follows
[{
"id": "1995",
"name": "Banahatti"
},
{
"id": "2356",
"name": "Bmbur"
}]
How can i able to achieve this In php.
PHP knows nothing about JSON, I would convert it into an array and then use array_filter, and then convert it back to JSON. Not super effecient, but certainly better than trying something like a regex. Something like the following:
$arr = json_decode($json, true);
$res = array_filter($arr, function($val) {
return substr($val['name'],0,1) == 'B';
});
$newJson = json_encode($res);
array_filter()
is a good option here. Just check every array object's name
property for a substring match. That might look like this:
$array = json_decode($input_json);
$search_term = 'B'; // populate your search value into this variable
$filtered_array = array_filter($array, function($obj) use ($search_term) {
// if you need to search any part of string
return strlen(strstr($obj->name, $search_term));
}
$filtered_json = json_encode($filtered_array);
Note, that this will search for your string in any part of the name
property. If you want to search only from the beginning, you can use the following inside the array_filter function:
return (strpos($obj->name, $search_term) === 0);