错误:通过php

时间:2017-10-17 08:37:38

标签: php json

Json数据(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代码:

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

我正在尝试根据条件(officename)获取元素的特定值(pincode=686563),但是当执行获取错误时

  

为foreach()提供的参数无效

1 个答案:

答案 0 :(得分:4)

删除[0]你想要遍历数组中的元素而不是第一个对象的属性,确保你的文件有有效的json,并且php能够读取它

{{1}}

演示:https://ideone.com/uUdNLt