0

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()

1
  • 1
    What does print_r($json_s[0]); gives me you? Commented Oct 17, 2017 at 8:41

1 Answer 1

4

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";
    }
}

demo :https://ideone.com/uUdNLt

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.