[英]How to Parse JSON with PHP?
I can do a var_dump, but when trying to access the values, I am getting errors about the values not being found.我可以执行 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
}
]
}
}
I used the following so far to try and parse it.到目前为止,我使用以下内容来尝试解析它。
$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).
Try:尝试:
$yourDecodedJSON = json_decode($yourJson)
echo $yourDecodedJSON->metrics->timers[0]->name;
Or you can:或者你可以:
$yourDecodedJSON = json_decode($yourJson, true); // forces array
echo $yourDecodedJSON['metrics']['timers'][0]->name;
In your case, you may want to..在你的情况下,你可能想要..
foreach($yourDecodedJSON['metrics']['timers'] as $timer){
echo $timer['name']; echo $timer['duration_ms']; // etc
}
If something fails, use:如果出现故障,请使用:
echo json_last_error_msg()
To troubleshoot further进一步排除故障
You need do it in following manner:-您需要按以下方式进行:-
<?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
}
?>
Output:- https://eval.in/407418输出:- https://eval.in/407418
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.