我想出了如何获得我想要的结果(几乎)。我的代码在最后一个 ] 之前的末尾添加了一个逗号,所以它不会很有效。我知道我可以使用 Json_encode 从我的外部 json 构建我的数组,但我很难过。我要么需要删除最后一个逗号,要么使用 json_encode (我迷路了)有什么更好的想法吗?
代码:
原始 JSON
[
{
"timestamp": 1383609600,
"localTimestamp": 1383609600,
"issueTimestamp": 1383609600,
"fadedRating": 4,
"solidRating": 0,
"swell": {
"minBreakingHeight": 4,
"absMinBreakingHeight": 3.836,
"maxBreakingHeight": 6,
"absMaxBreakingHeight": 5.992,
"unit": "ft",
"components": {
"combined": {
"height": 7,
"period": 13,
"direction": 82.64,
"compassDirection": "W"
},
"primary": {
"height": 7,
"period": 13,
"direction": 72.94,
"compassDirection": "WSW"
}
}
}
]
PHP 得到想要的结果
<?php
$url = 'http://magicseaweed.com/api/API_KEY/forecast/?spot_id=1';
$JSON = file_get_contents($url);
$data = json_decode($JSON,true);
echo "[";
foreach ($data as $record) {
echo "[";
echo "{$record['timestamp']}";
echo ",";
echo "{$record['swell']['absMinBreakingHeight']}";
echo "]";
echo ",";
}
echo "]";
?>
返回:期望的结果减去最后一个逗号(编辑长度)
[
[
1383609600,
3.836
],
[
1383620400,
4.081
],
]
最好的方法是什么?