从使用foreach循环构造的JSON中删除最后一个逗号

时间:2014-01-09 13:28:39

标签: php arrays json foreach comma

我有这个脚本构造一个JSON:

echo "{";
echo "\"name\": \"flare\","."\n";
echo "\"children\": ["."\n";
foreach($tree as $tag => $customer){
    foreach($customer as $customerId => $order){
        echo "{\"name\":\"".$customerId."\",";
        echo "\"children\": ["."\n";
            foreach($order as $orderId => $orderTotal){
                echo "{\"name\": \"".$orderId."\", \"size\": \"".$orderTotal."\"},";
            }
        echo "]";
        echo "},";
    }
}
echo "]";
echo "}";

$ Tree,$ customer和$ order是多维数组的级别,用于重复循环以查找数组的特定“$ order”级别。生成的JSON如下JSON:

{
"name":"flare",
"children":[
    {
    "name":"4",
    "children":[
    {
        "name":"17",
        "size":"104.15"
        },
        {
        "name":"18",
        "size":"104.15"
        },
        {
        "name":"23",
        "size":"104.15"
        },
        {
        "name":"25",
        "size":"104.15"
        }, // Remove this comma
    ]
    },
    {
    "name":"12",
    "children":[
        {
        "name":"36",
        "size":"280.00"
        },
        {
        "name":"37",
        "size":"384.15"
        },
        {
        "name":"38",
        "size":"664.15"
        },
        {
        "name":"43",
        "size":"112.00"
        },
        {
        "name":"278",
        "size":"235.20"
        },
        {
        "name":"281",
        "size":"117.60"
        },
        {
        "name":"298",
        "size":"117.60"
        }, // Remove this comma
    ]
    },
    {
    "name":"16",
    "children":[
        {
        "name":"60",
        "size":"112.00"
        }, // Remove this comma
    ]
    },
    {
    "name":"17",
    "children":[
        {
        "name":"236",
        "size":"235.20"
        },
        {
        "name":"295",
        "size":"117.60"
        },
    ]
    }, // Revome this comma
]
}

一切正常,但我必须删除最后一个逗号,因为它生成错误解析JSON。我不能使用substr()和rtrim(),因为那些删除删除了JSON中的所有逗号,而不是最后一个。

问候。

已更新 现在我有两个级别的逗号要删除。

1 个答案:

答案 0 :(得分:2)

正如有人已经说过的,不要尝试手动构建JSON字符串,在php中构建数据结构并使用json_encode

$data = array("name" => "flare", "children" => array());
foreach($tree as $tag => $customer){
    foreach($customer as $customerId => $order){
        $_data = array("name" => $customerId, "children" => array());
        foreach($order as $orderId => $orderTotal){
              $_data["children"][] = array("name" => $orderId, "size" => $orderTotal);
        }
        $data["children"][] = $_data;
    }
}
echo json_encode($data, JSON_PRETTY_PRINT);