Remove last comma from JSON constructed with foreach loop

I Have this script the construct a 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 and $order are levels of a multidiomensional array to repeit the loops to find a specific "$order" level of the array. The produced JSON the following 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
]
}

Everything is OK but I have to remove the last comma because Its generating errors parsing the JSON. I can't use substr() and rtrim() because those remove remove all comma in the JSON, not the last.

Regards.

UPDATED Now I have two levels of commas to remove.


正如有人已经说过,不要尝试手动构建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);
链接地址: http://www.djcxy.com/p/47288.html

上一篇: 我应该使用哪个@NotNull Java注释?

下一篇: 从用foreach循环构建的JSON中删除最后一个逗号