我怎样才能以这种格式回应这个json?
123456789 - mypage3 - 2015-05-06 09:34:02
- mypage2 - 2015-05-06 09:34:02
- mypage1 - 2015-05-06 09:34:02
999999 - mypage4 - 2015-05-06 09:34:02
这是JSON
{"hash":"123456789","pages":[{"page":"mypage3","last_access_time":"2015-05-06 09:34:02"},{"page":"mypage2","last_access_time":"2015-05-06 09:34:02"},{"page":"mypage1","last_access_time":"2015-05-06 09:34:02"}]}
{"hash":"999999","pages":[{"page":"mypage4","last_access_time":"2015-05-06 09:34:02"}]}
以下是我现在所拥有的:
$appResult = array();
while($row = mysql_fetch_array($sql)) {
$json_res_obj = json_decode($row['json_prt']);
echo $row[json_prt];
}
答案 0 :(得分:1)
在这里考虑这个PHP代码,它仅适用于第一个JSON字符串,但您明白了这一点:
<?php
$json = '{
"hash": "123456789",
"pages": [
{
"page": "mypage3",
"last_access_time": "2015-05-06 09:34:02"
},
{
"page": "mypage2",
"last_access_time": "2015-05-06 09:34:02"
},
{
"page": "mypage1",
"last_access_time": "2015-05-06 09:34:02"
}
]
}';
$data = json_decode($json,true);
echo $data['hash'] . " - ";
foreach($data['pages'] as $rows) {
echo $rows['page'] . " - " . $rows['last_access_time'] . "<br>";
}
?>
答案 1 :(得分:0)
使用此代码
<?php
$data = '{"hash":"123456789","pages":[{"page":"mypage3","last_access_time":"2015-05-06 09:34:02"},{"page":"mypage2","last_access_time":"2015-05-06 09:34:02"},{"page":"mypage1","last_access_time":"2015-05-06 09:34:02"}]}';
$data = json_decode($data);
echo $data->hash . "<br>";
$pages = $data->pages;
if(isset($data->pages)){
foreach($pages as $key => $value){
echo $value->page . "-" . $value->last_access_time . "<br>";
}
}
?>
答案 2 :(得分:0)
您可以使用此代码添加一些格式
$row['json_prt'] = '{"hash":"123456789","pages":[{"page":"mypage3","last_access_time":"2015-05-06 09:34:02"},{"page":"mypage2","last_access_time":"2015-05-06 09:34:02"},{"page":"mypage1","last_access_time":"2015-05-06 09:34:02"}]}';
$json_res_obj = json_decode($row['json_prt']);
echo '<pre>';
foreach($json_res_obj->pages as $page)
echo ' - '.$page->page.' - '.$page->last_access_time.'<br>';
更新:
while($row = mysql_fetch_array($sql)) {
$json_res_obj = json_decode($row['json_prt']);
echo '<pre>';
foreach($json_res_obj->pages as $page)
echo ' - '.$page->page.' - '.$page->last_access_time.'<br>';
}