2013-07-17 43 views
0

我有以下的JSON響應的例子(通常是一個較長的響應):如何通過它的索引來訪問JSON財產

"responseHeader":{ 
    "status":0, 
    "QTime":2, 
    "params":{ 
    "indent":"true", 
    "start":"0", 
    "q":"hi", 
    "wt":"json", 
    "rows":"2"}}, 
"response":{"numFound":69,"start":0,"docs":[ 
    { 
    "id":335, 
    "Page":127, 
    "dartext":" John Said hi !  ", 
    "Part":1}, 
    { 
    "id":17124, 
    "Page":127, 
    "Tartext":" Mark said hi ", 
    "Part":10}] 
}} 

我只想用字符串類型,取得財產的問題是屬性的名稱是不恆定的,所以我不能使用類似的東西:

$obj =json_decode(file_get_contents($data)); 
$count = $obj->response->numFound; 

for($i=0; $i<count($obj->response->docs); $i++){ 
    echo $obj->response->docs[$i]->dartext; 
} 

因爲在另一個對象它不是dartext它是Tartext。

如何通過索引訪問第三個屬性而不是名稱?

+0

你先找出其中很重要關鍵在於。即使它存在(使用下面的答案,你可以弄清楚) - 不保證對象鍵將始終以相同的順序...請參閱[this](http://stackoverflow.com/a/5525820/) 3249501)優秀的答案 – GrayedFox

回答

1

更好的方法是,檢查註冊表項存在,因爲結果的順序可以改變

<?php 
$response = $obj->response; 
foreach($response->docs as $doc) { 
    if (isset($doc->dartext)) { 
     $text = $doc->dartext; 
    } elseif (isset($doc->Tartext)) { 
     $text = $doc->Tartext; 
    } else { 
     $text = ''; 
    } 
} 
0

從文檔:

mixed json_decode (string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]])

如果使用json_decode(file_get_contents($data), true)它會返回一個數組。

之後,你可以做這樣的事情來通過索引而不是密鑰訪問數組。

$keys = array_keys($json); 
echo $json[$keys[2]]; 
1

你可以試試這個:

$my_key = array(); 
$obj =json_decode(file_get_contents($data)); 
$count = $obj->response->numFound; 
$k =1; 
foreach ($obj->response->docs as $k => $v) { 
    if ($k == 3) { 
     $my_key[$k] = $v; // Here you can put your key in 
    } 
    $k++; 
}