簡體   English   中英

如何用 PHP 解析 JSON?

[英]How to Parse JSON with PHP?

我可以執行 var_dump,但是在嘗試訪問值時,我收到有關未找到值的錯誤。

    {
  "metrics": {
    "timers": [
      {
        "name": "com.android.timer.launchtime",
        "startTime": 1232138988989,
        "duration_ms": 1900
      },
      {
        "name": "com.android.timer.preroll-load-time",
        "startTime": 1232138988989,
        "duration_ms": 1000
      }
    ]
  }
}

到目前為止,我使用以下內容來嘗試解析它。

$json_file = file_get_contents('test.json'); 
$json_a = json_decode($json_file,true);


var_dump(json_decode($json_file)); //This works

echo $json_a['name']; //I want to print the name of each (from timers).

嘗試:

$yourDecodedJSON = json_decode($yourJson)

echo $yourDecodedJSON->metrics->timers[0]->name;

或者你可以:

$yourDecodedJSON = json_decode($yourJson, true); // forces array

echo $yourDecodedJSON['metrics']['timers'][0]->name;

在你的情況下,你可能想要..

foreach($yourDecodedJSON['metrics']['timers'] as $timer){

    echo $timer['name']; echo $timer['duration_ms']; // etc

}

如果出現故障,請使用:

echo json_last_error_msg()

進一步排除故障

您需要按以下方式進行:-

<?php

 $data =  '{
  "metrics": {
    "timers": [
      {
        "name": "com.android.timer.launchtime",
        "startTime": 1232138988989,
        "duration_ms": 1900
      },
      {
        "name": "com.android.timer.preroll-load-time",
        "startTime": 1232138988989,
        "duration_ms": 1000
      }
    ]
  }
}';
$new_array = json_decode($data); //convert json data into array
echo "<pre/>";print_r($new_array); //print array
foreach ($new_array->metrics->timers as $new_arr){ // iterate through array
    echo $new_arr->name.'<br/>'; // rest you can do also same   
}
?>

輸出:- https://eval.in/407418

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM