2013-04-03 67 views
2

這裏是我的JSON代碼:如何從嵌套的JSON數據中獲取值?

{ 
    "query": { 
     "count": 2, 
     "created": "2013-04-03T09:47:03Z", 
     "lang": "en-US", 
     "results": { 
      "yctCategories": { 
       "yctCategory": { 
        "score": "0.504762", 
        "content": "Computing" 
       } 
      }, 
      "entities": { 
       "entity": [ 
        { 
         "score": "0.902", 
         "text": { 
          "end": "19", 
          "endchar": "19", 
          "start": "0", 
          "startchar": "0", 
          "content": "Computer programming" 
         }, 
         "wiki_url": "http://en.wikipedia.com/wiki/Computer_programming" 
        }, 
        { 
         "score": "0.575", 
         "text": { 
          "end": "51", 
          "endchar": "51", 
          "start": "41", 
          "startchar": "41", 
          "content": "programming" 
         } 
        } 
       ] 
      } 
     } 
    } 
} 

以下是我的PHP代碼

$json_o = json_decode($json,true); 
echo "Json result:</br>"; 
echo $json; // json 
echo "</br></br>"; 
echo "Value result:</br>"; 
$result = array(); 
//$entity = $json_o['query']['results']['entities']['entity']; 
foreach ($json_o['query']['results']['entities']['entity'] as $theentity) 
foreach ($theentity['text'] as $thetext){ 
    $result[] = $thetext['content']; 
} 
print_r($result); 

我的期望是得到的實體內容的價值,這是「計算機編程」和「編程「。

我已經在四處搜尋,但還是找到了解決方案。

我的PHP代碼的結果是:

Array ([0] => 1 [1] => 1 [2] => 0 [3] => 0 [4] => C [5] => 5 [6] => 5 [7] => 4 [8] => 4 [9] => p) 

回答

0

將您的foreach更改爲:

$result = array(); 
foreach ($json_o['query']['results']['entities']['entity'] as $theentity) { 
    $result[] = $theentity['text']['content']; 
} 
print_r($result); 

$theentity['text']是keys =>值的數組。您只需訪問密鑰content,而不是循環遍歷所有條目。

另一種方式,你可以做到這一點(雖然這是一個糟糕的選擇)是:

foreach($theentity['text'] as $key => $value) { 
    if('content' === $key) { 
     $result[] = $value; 
    } 
} 

我提供這個第二個例子來說明爲什麼原來的代碼沒有工作。

更新

要訪問其他屬性,如yctCategories只是做類似

$categories = array(); 
foreach ($json_o['query']['results']['yctCategories'] as $yctCategory) { 
    $categories[] = $yctCategory['content']; 
} 
print_r($categories); 
0

刪除第二個的foreach和使用類似http://jsonlint.com/可能使你更容易看到JSON是如何構成與$result[] = $theentity['text']['content'];

更換。或者只是var_dump(或print_rjson_decode的輸出。

+0

THX的東西,我也用** ** jsonlint.com不必要的分解結構 –

1

使用此循環

foreach ($json_o['query']['results']['entities']['entity'] as $theentity) 
{ 
    $result[] = $theentity['text']['content']; 
} 

http://codepad.viper-7.com/tFxh1w

輸出陣列([0] =>計算機編程[1] =>編程)

0

使用簡單代碼:

$array = $json_o['query']['results']['entities']['entity']; 

foreach($array as $v){ 
    echo $v['text']['content']; 
} 
+0

複製數據,沒有理由在這裏效率低下。 –

+0

@RickBurgess好的,但提供更多的可讀性:)和性能編輯 – 2013-04-03 11:17:33

+0

@Akam thx的澄清..它給了我一些其他選項在編寫代碼 –