使用PHP列出JSON

时间:2016-11-16 15:13:26

标签: php json

我需要从results属性中列出非空的JSON键。 以下是json文件内容的链接:https://eval.in/678910 我一直在尝试使用此代码,但我不知道如何添加检查空键的条件。结果应该是:
AirBagLocFront:第一排(驾驶员和乘客)
AirBagLocKnee:第一排(驾驶员和乘客)
等等。

$jfo = json_decode($json_file);

if ($jfo != '' && $jfo !== null) {

// read the Name value
foreach($jfo as $item) {

    // to know what's in $item
    echo '<pre>'; var_dump($item);
}

}

2 个答案:

答案 0 :(得分:5)

首先,您需要返回一个数组,展平数组(使用RecursiveIteratorIterator中的RecursiveArrayIteratorStandard PHP Library(对于很多事情非常方便),然后测试空白值:

$jfo = json_decode($json_file, true); // return an array, not an object

$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($jfo));
foreach($it as $k => $v) {
    if(!empty($v)) { // test to see if the value is NOT empty
        echo $k . " value is " . $v . "<br />";
    }
}

返回:

Count value is 115
Message value is Results returned successfully
SearchCriteria value is VIN(s): 1G1PE5S95B7254749
AirBagLocFront value is 1st Row (Driver & Passenger)
AirBagLocKnee value is 1st Row (Driver & Passenger)
AirBagLocSide value is 1st & 2nd Rows
BodyClass value is Sedan/Saloon
DisplacementCC value is 1400.0
DisplacementCI value is 85.43324173262
DisplacementL value is 1.4
Doors value is 4
EngineConfiguration value is In-Line
EngineCylinders value is 4
EngineModel value is LUJ
ErrorCode value is 0 - VIN decoded clean. Check Digit (9th position) is correct
FuelInjectionType value is Multipoint Fuel Injection (MPFI)
FuelTypePrimary value is Gasoline
Make value is CHEVROLET
Manufacturer value is GENERAL MOTORS LLC
ManufacturerId value is 984
Model value is Cruze
ModelYear value is 2011
OtherEngineInfo value is HO, ALUM GME
OtherRestraintSystemInfo value is Airbags: Roof Side - all seating rows
PlantCity value is Lordstown
PlantCompanyName value is GMNA
PlantCountry value is United States (USA)
PlantState value is Ohio
SeatBeltsAll value is Manual
TransmissionStyle value is Automatic
Trim value is LT
Turbo value is Yes
VIN value is 1G1PE5S95B7254749
ValveTrainDesign value is Dual Overhead Cam (DOHC)
VehicleType value is PASSENGER CAR
Windows value is 4

答案 1 :(得分:0)

您可以使用

foreach($jfo as $key => $value)

$ key是数组的关键 $ value是$ jfo [$ key]

的值