2012-01-19 30 views
0

我是新來的php。我需要一些快速幫助json_decode/php。我需要在數組中獲得g91的值,我該怎麼做?我想有,我們可以傳遞給json_decode一些遞歸值...如何使用json_decode提取內部信息

{ 
    "e": "none", 
    "f": "test", 
    "g": [ 
     { 
      "g1": "text2", 
      "g9": { 
       "text3": { 
        "g91": 0, 
        "g92": [ 
         "text5" 
        ] 
       } 
      } 
     }, 
     { 
      "g1": "text1",   
      "g9": { 
       "text4": { 
        "g91": 0, 
        "g92": [ 
         "text6", 
         "text7" 
        ] 
       } 
      } 
     } 
    ] 
} 

請注意,文字3不fixed..in下一個記錄,我有文本4 ..

謝謝!

+0

的[從JSON獲取信息] Dup的(http://stackoverflow.com/questions/3879472 /),[從JSON數組中獲取「得分」](http://stackoverflow.com/questions/8447084/) – outis

回答

0

解碼後,你會得到一個PHP數組,只是去所需的索引:

$myJson['g'][0]['g9']['text3']['g91']; 

但你可以做一些遞歸循環找到所有你該數組中搜索的結果。

以在陣列文檔看看從PHP:http://br2.php.net/manual/en/book.array.php

0
$json = '{ 
    "e": "none", 
    "f": "test", 
    "g": [ 
     { 
      "g1": "text2", 
      "g9": { 
       "text3": { 
        "g91": 0, 
        "g92": [ 
         "text5" 
        ] 
       } 
      } 
     }, 
     { 
      "g1": "text1",   
      "g9": { 
       "text4": { 
        "g91": 0, 
        "g92": [ 
         "text6", 
         "text7" 
        ] 
       } 
      } 
     } 
    ] 
}'; 
$result = json_decode($json); 
var_dump(array_merge($result->g[0]->g9->text3->g91, $result->g[1]->g9->text3->g91)); 
5

通行證TRUE到json_decode作爲第二個參數

$output = json_decode($input,TRUE); 

比橫穿陣列。它應該像

$output['g'][0]['g9']['text3']['g91'] 

參考json_decode

+0

但text3不固定..所以在循環中引用時,會在這裏得到什麼值? – xyz

+0

這給出了錯誤PHP的致命錯誤:不能使用stdClass類型的對象作爲數組在....在我嘗試引用輸出這樣的行號.. – xyz

0

我更新了JSON用於測試目的:

<script type="text/javascript"> 
    var json ={ 
     "e": "none", 
     "f": "test", 
     "g": [ 
      { 
       "g1": "text2", 
       "g9": { 
        "text3": { 
         "g91": 83, 
         "g92": [ 
          "text5" 
         ] 
        } 
       } 
      }, 
      { 
       "g1": "text1",   
       "g9": { 
        "text4": { 
         "g91": 12, 
         "g92": [ 
          "text6", 
          "text7" 
         ] 
        } 
       } 
      } 
     ] 
    } 
    var arr=json["g"]; 
    for(key in arr){ 
     var obj=arr[key]["g9"]; 
     for(tex in obj) 
     { 
     alert(obj[tex]["g91"]); 
     } 
    } 
</script> 
+0

當我運行它爲「php file.php」,我只是得到這個文件本身的轉儲..(file.php包含上面的代碼) – xyz