Click here to Skip to main content
15,844,903 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi All,

I want to parse a JSON files which contains data in the format as shown below,

[
{
"Country": "United States"
"States": [
{
"Cities": [
"Abbeville",
"Abernant",
"Adamsville",
"Addison"
],
"State": "AL"
},
{
"Cities": [
"Adak",
"Akiak",
"Akutan",
"Ambler"
],
"State": "AK"
},
]
},
{
"Country": "Canada"
"States": [
{
"Cities": [
"Barrie",
"Belleville",
"Brampton",
"Brant"
],
"State": "ON"
},
{
"Cities": [
"Acton Vale",
"Alma",
"Amos",
"Amqui",
"Asbestos"
],
"State": "QC"
},
]
}

]

From above JSON format, I want to get list of all Country names, State names,City Names.

First,I want all the country names list. Then when I pass country name as "Canada" then all its states should be fetched and so on to get the city names of respective country ,state and city.
Posted

First, read your json data into a string.
PHP
$strJson = file_get_contents('data.json');


Second, decode the json data into an array variable
PHP
$arrJson = json_decode($strJson);
 
Share this answer
 
Below is the code that I have used to solve my problem,

Condition 1] To get list of all countries

$jsonDecode=json_decode(file_get_contents(file_get_contents("D:\abc.json")),true);
$result=array();

foreach($jsonDecode as $countries)
{
$result[]=$countries{'Country'};
}
=============================
Condition 2] If Country name is passed then get all states list

$jsonDecode=json_decode(file_get_contents(file_get_contents("D:\abc.json")),true);
$result=array();

foreach($jsonDecode as $countries)
{
if($countries{'Country'}==$countryName)
{
foreach($countries{'States'} as $states)
{
$result[]=$states{'State'};
}
}
}
=============================
Condition 3] If Country,State is passed then get Cities list

$jsonDecode=json_decode(file_get_contents(file_get_contents("D:\abc.json")),true);
$result=array();

foreach($jsonDecode as $countries)
{
if($countries{'Country'}==$countryName)
{
foreach($countries{'States'} as $states)
{
if($states{'State'}==$stateName)
{
foreach($states{'Cities'} as $cities)
{
$result[]=$cities;
}
}
}
}
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900