Deekshith's avatar

Filter city based on state in JSON in php

i am using city and state list json from below link,

https://github.com/nshntarora/Indian-Cities-JSON/blob/master/cities.json

Format is like below,

[
    {
        "id": "1",
        "name": "Mumbai",
        "state": "Maharashtra"
    },
    {
        "id": "2",
        "name": "Delhi",
        "state": "Delhi"
    },
    {
        "id": "3",
        "name": "Bengaluru",
        "state": "Karnataka"
    },
	{
        "id": "4",
        "name": "Mysore",
        "state": "Karnataka"
    },
]

Here state is repeating for different cities now i want to display all states in select box for that i want to fetch state value which are unique and display in select box. then on change of state i want to fetch all data which matches state name.

i am storing this json in .json file and fetching the data like below,

$getjson = file_get_contents("./assets/statescities.json");
$statesresult = json_decode($getjson, true);

Any help? Thank you

0 likes
4 replies
tykus's avatar
$states = collect($stateresult)->unique('state');
$citiesInState =  collect($stateresult)->where('state', $selectedState);
tykus's avatar
tykus
Best Answer
Level 104

@Deekshith in that case the array_ method will work:

$states = array_unique(array_map(fn ($item) => $item['state'], $cities));
$selectedCities = array_filter($cities, fn ($city) => $city['state'] == $selectedState);

Please or to participate in this conversation.