如何用PHP解析JSON?

时间:2015-07-28 13:52:24

标签: php json

我可以执行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).

2 个答案:

答案 0 :(得分:1)

尝试:

$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()

进一步排查

答案 1 :(得分:0)

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

<?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