2

我想出了如何获得我想要的结果(几乎)。我的代码在最后一个 ] 之前的末尾添加了一个逗号,所以它不会很有效。我知道我可以使用 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
    ],
] 

最好的方法是什么?

4

3 回答 3

3

冒着在没有明确问题的情况下回答的风险,只需构建一个你想要的数组并对其进行编码:

foreach ($data as $record) {
    $array[] = array($record['timestamp'], $record['swell']['absMinBreakingHeight']);
}
echo json_encode($array); 
于 2013-11-05T18:19:30.003 回答
0

您可以将数据存储在临时数组中并使用 implode。

$data = json_decode($JSON,true);
$out = array();
foreach ($data as $record) {
    $out[] = "[{$record['timestamp']},{$record['swell']['absMinBreakingHeight']}]";
}   
echo "[" . implode(',', $out) . "]";

最好使用json_encode。像这样 :

$data = json_decode($JSON,true);
$out = array();
foreach ($data as $record) {
    $out[] = array($record['timestamp'], $record['swell']['absMinBreakingHeight']);
}   
echo json_encode($out);

这段代码更简单。

于 2013-11-05T18:18:21.537 回答
0

简而言之..删除字符串中的最后一个字符(此处为逗号)可以通过以下方式完成:

$string = rtrim($string, ',');

检查更详细的参考http://php.net/manual/en/function.rtrim.php

于 2013-11-05T19:28:03.100 回答