Json_encode还是删除最后一个逗号?

时间:2013-11-05 18:08:53

标签: php json

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

最好的方法是什么?

3 个答案:

答案 0 :(得分:2)

在没有明确问题的情况下回答风险:

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

答案 1 :(得分: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);

这段代码更简单。

答案 2 :(得分:0)

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

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

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