Json_encode或删除最后一个逗号


Json_encode or remove last comma?

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

最好的方法是什么?

冒着

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

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

您可以将数据存储在临时数组中并使用 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);

此代码甚至更简单。

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

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

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

**To remove the comma if there is no further array or object. Use the PHP chop function**. One can do like this example:-
    $jsonArrayString=[
      { "id":1, ---- , 'type':'open','draft':true},
      {"id":2, ---- , 'type':'open', 'draft':false},
      {"id":3, ---- , 'type':'closed', 'draft':false},
    ]
    $response = chop($jsonArrayString,",]");$response.=$string."]";
    $jsonArray = json_decode($response, true);
    
    Output:- [
      { "id":1, ---- , 'type':'open','draft':true},
      {"id":2, ---- , 'type':'open', 'draft':false},
      {"id":3, ---- , 'type':'closed', 'draft':false}
    ]