2013-07-22 34 views
1

我試圖分析一些政府數據。這裏的JSONJSON PHP無法通過嵌套數組瀏覽

{ 
"results": [ 
    { 
     "bill_id": "hres311-113", 
     "bill_type": "hres", 
     "chamber": "house", 
     "committee_ids": [ 
      "HSHA" 
     ], 
     "congress": 113, 
     "cosponsors_count": 9, 
     "enacted_as": null, 
     "history": { 
      "active": false, 
      "awaiting_signature": false, 
      "enacted": false, 
      "vetoed": false 
} 

這裏是PHP

foreach($key['results'] as $get_key => $value){ 
    $bill_buff .= 'Bill ID: ' . $value['bill_id'] . '<br/>'; 
    $bill_buff .= 'Bill Type: ' . $value['bill_type'] . '<br/>'; 
    $bill_buff .= 'Chamber: ' . $value['chamber'] . '<br/>'; 
    $bill_buff .= 'Committee IDs: ' . $value['committee_ids'] . '<br/>'; 
    $bill_buff .= 'Congress: ' . $value['congress'] . '<br/>'; 
    $bill_buff .= 'Cosponsor Count: ' . $value['cosponsors_count'] . '<br/>'; 
    $bill_buff .= 'Enacted As: ' . $value['enacted_as'] . '<br/>'; 
    $bill_buff .= 'History: {' . '<br/>'; 
    $history = $value['history']; 
    $bill_buff .= 'Active: ' . $history['active'] . '<br/>'; 
    $bill_buff .= 'Awaiting Signature: ' . $history['awaiting_signature'] . '<br/>'; 
    $bill_buff .= 'Enacted: ' . $history['enacted'] . '<br/>'; 
    $bill_buff .= 'Vetoed: ' . $history['vetoed'] . '}<br/>'; 
} 

它不會顯示歷史{活動,等待簽名,制定或否決}。我試圖做$value['history']['active'],以及創建一個變量來捕獲信息,然後使用該$catch['active'],但仍然無法獲得結果。

這已經讓我討厭了一個多星期了,而且我看了足夠長的時間來決定我需要尋求幫助。任何人都可以幫我嗎?

P.S.我還的print_r($歷史)已經去它告訴我:

陣列([活躍] => [awaiting_signature] => [頒佈] => [否決] =>)

+1

'$ history ['active']'是'false'。當轉換爲字符串時,由於您將它連接起來,所以它變成了''''(空字符串)。也許你想要'活躍:'。 ($ history ['active']?'true':'false')' –

+2

當'false'轉換爲字符串時,它返回一個空字符串,而不是字符串'「false」'。 – Barmar

回答

0

FALSE沒有字符串值,這意味着它不會在PHP中打印。你不會看到它與echo,print甚至fwrite(STDOUT...

但是,您將會看到所有與var_dump

var_dump($key['results']); 

// outputs: 
    array(1) { 
    [0]=> 
    array(8) { 
     ["bill_id"]=> 
     string(11) "hres311-113" 
     ["bill_type"]=> 
     string(4) "hres" 
     ["chamber"]=> 
     string(5) "house" 
     ["committee_ids"]=> 
     array(1) { 
     [0]=> 
     string(4) "HSHA" 
     } 
     ["congress"]=> 
     int(113) 
     ["cosponsors_count"]=> 
     int(9) 
     ["enacted_as"]=> 
     NULL 
     ["history"]=> 
     array(4) { 
     ["active"]=> 
     bool(false) 
     ["awaiting_signature"]=> 
     bool(false) 
     ["enacted"]=> 
     bool(false) 
     ["vetoed"]=> 
     bool(false) 
     } 
    } 
    } 
+0

太棒了,謝謝!我能夠看到其中一個有效值爲'1',並且您的解釋是有意義的。萬分感謝! –

1

當您讀取值時,false被視爲布爾值而不是字符串。當您試圖回顯布爾值false(例如嘗試print false;)時,PHP不顯示任何內容。

Interactive shell 

php > var_dump(false); 
bool(false) 
php > print_r(false); 
php > 

看到這個問題的可能解決方案:您還可以進一步通過比較print_r輸出到var_dump輸出,如驗證這一點 How to Convert Boolean to String

的基本概況是,你需要測試的值,然後輸出一個字符串。

+0

謝謝!我很感謝澄清! –