fredcampbell fredcampbell - 22 days ago 9
JSON Question

Listing JSON using PHP

I need to list JSON keys from results attribute which are NOT empty.
Here is the link to the json file content: https://eval.in/678910
I have been trying something with this code but i am not sure how to add condition which checks out empty keys. The results should be:

AirBagLocFront:1st Row (Driver & Passenger)

AirBagLocKnee: 1st Row (Driver & Passenger)

and so on.

$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);
}

}

Answer

First you need to return an array, flatten the array (using RecursiveIteratorIterator and RecursiveArrayIterator from the Standard PHP Library (which is quite handy for a lot of things) and then test for the blank value:

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

Returns:

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