2016-11-16 47 views
1

我需要列出結果屬性中不爲空的JSON密鑰。 這裏是json文件內容的鏈接:https://eval.in/678910 我一直在嘗試這個代碼的東西,但我不知道如何添加檢查空鍵的條件。結果應該是:
AirBagLocFront:第1行(司機&客)
AirBagLocKnee:第1行(司機&客)
等。使用PHP清單JSON

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

} 
+0

這仍然不能格式,我需要返回鍵和值。你能幫我嗎? – fredcampbell

+0

添加第二個'true'參數'json_decode($ json_file,true)',然後執行foreach($ jfo ['Results']作爲$ item)'。這看起來像你想要的方式嗎? –

+0

@PradyutManna告訴你的是,使用'true'標誌返回一個數組,而不是一個對象。該數組將是多維的,所以您將不得不使用遞歸函數來處理每個鍵/值對,測試該值是否爲空,然後將該鍵添加到列表中。 –

回答

5

首先值,壓平陣列(使用來自Standard PHP LibraryRecursiveIteratorIteratorRecursiveArrayIterator(這對於很多事情來說非常方便),然後測試空白值:

$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

謝謝傑伊,它工作得很好!我只有一個問題,我如何訪問數組中的特定鍵?我試過這個,但它不起作用「$ make = $ jfo-> Results [0] - > Make; – fredcampbell

+0

因爲它是一個數組,你必須使用數組表示法:'echo $ jfo ['Results'] [0 ] ['Make'];' –

+1

它也可以工作!再次感謝您的幫助! – fredcampbell

0

您可以使用

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

$關鍵是陣列和 $價值的關鍵是你需要返回一個數組$ JFO [$關鍵]

+0

我應該怎麼回聲呢? – fredcampbell

+0

'code' foreach($ jfo as $ key => $ value) –

+0

foreach($ jfo as $ key => $ value){0}。';'。$ value); } –