Json data(pincodes.json):
[{
"officename": "Netajinagar B.O",
"pincode": 744207,
"taluk": "Hut Bay",
"districtname": "South Andaman",
"statename": "ANDAMAN \u0026 NICOBAR ISLANDS"
}, {
"officename": "Tushnabad B.O",
"pincode": 744103,
"taluk": "Port Blair",
"districtname": "South Andaman",
"statename": "ANDAMAN \u0026 NICOBAR ISLANDS"
}, {
"officename": "Uttara B.O",
"pincode": 744209,
"taluk": "Rangat",
"districtname": "North And Middle Andaman",
"statename": "ANDAMAN \u0026 NICOBAR ISLANDS"
}]
PHP code:
<?php
$string = file_get_contents("pincodes.json");
$json_s = json_decode($string);
foreach($json_s[0] as $item)
{
if($item->pincode == "686563")
{
echo $item->officename;
}else{
echo "Item not found";
}
}
I am trying to fetch a particular value of an element(officename
) based on the criteria(pincode=686563
) but when executes getting error
Invalid argument supplied for foreach()
Remove [0] you want to loop over the elements in the array not over the properties of the first object, make sure your file has valid json,and php is able to read it
foreach($json_s as $item)
{
if($item->pincode == "686563")
{
echo $item->officename;
}else{
echo "Item not found";
}
}