2016-04-28 77 views
0

我試圖使用json_decode 但我認爲[]在結果的任何一端都與它有關。解析PHP中的JSON字符串以顯示其內容

我需要訪問此JSON的某些部分。

在PHP中我做的:

<?php 
    $arr = json_decode($json, true); 
    print $arr['ua']['rawUa']; 
?> 

實際的JSON(從這裏開始)爲:

[ 
    { 
    "meta": { 
     "name": "ua-parser", 
     "repo": "https://github.com/tobie/ua-parser", 
     "version": "0.3.5" 
    }, 
    "ua": { 
     "rawUa": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2718.0 Safari/537.36", 
     "string": { 
     "family": "Chrome", 
     "major": "52", 
     "minor": "0", 
     "patch": "2718" 
     }, 
     "family": "Chrome", 
     "major": 52, 
     "minor": 0, 
     "patch": 2718, 
     "device": { 
     "family": "Other" 
    } 
    }, 
    "os": { 
    "string": { 
     "family": "Mac OS X", 
     "major": "10", 
     "minor": "11", 
     "patch": "1", 
     "patchMinor": null 
    }, 
    "family": "Mac OS X", 
    "major": "10", 
    "minor": "11", 
    "patch": "1" 
    } 
}, 
{ 
    "meta": { 
    "name": "ua-parser-js", 
    "repo": "https://github.com/faisalman/ua-parser-js", 
    "version": "" 
    } 
}, 
{ 
    "meta": { 
    "name": "platform.js", 
    "repo": "https://github.com/bestiejs/platform.js/", 
    "version": "1.3.0" 
    }, 
    "ua": { 
     "name": "Chrome", 
     "version": "52.0.2718.0", 
     "layout": "Blink" 
    }, 
    "os": { 
     "os": { 
     "architecture": 32, 
     "family": "OS X", 
     "version": "10.11.1" 
     } 
    }, 
    "device": { 
     "product": null, 
     "manufacturer": null, 
     "description": "Chrome 52.0.2718.0 on OS X 10.11.1" 
    } 
    } 
] 
+1

由於包封的'[...]'的結果是一個數組,只有1元件是它雖然。因此,要訪問第一個元素,請使用'$ arr [0] ['ua'] ['key']'。使用'print_r'輸出變量有助於在代碼中找到錯誤... – giorgio

回答

0

嘗試使用:

print $arr[0]['ua']['rawUa'];

+0

您的傳奇,非常感謝 – SAFC

0

只使用第指數0.你的數組第一個索引從0開始。

$arr = json_decode($json, true); 

echo $arr[0]['ua']['rawUa']; 
0

試試這個,你必須從指數零獲取數據,檢查嘗試打印陣列var_dump($arr);

$arr = json_decode($data, true); 

print $arr[0]['ua']['rawUa']; 
0

使用foreach循環讀取所有記錄。

$arr = json_decode($json, true); 

foreach($arr as $row) 
{ 
    if(isset($row['ua']['rawUa']) 
    { 
     echo $row['ua']['rawUa']; 
    } 
} 

對於單記錄使用array index [0]

print $arr[0]['ua']['rawUa']; 
0

的var_dump($ ARR);

結果部分:

array (size=3) 
    0 => 
    array (size=3) 
     'meta' => 
     array (size=3) 
      'name' => string 'ua-parser' (length=9) 
      'repo' => string 'https://github.com/tobie/ua-parser' (length=34) 
      'version' => string '0.3.5' (length=5) 
     'ua' => 
     array (size=7) 
      'rawUa' => string 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2718.0 Safari/537.36' (length=119)