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

I Have this script the construct a JSON:

echo "{";
echo "\"name\": \"flare\","."
";
echo "\"children\": ["."
";
foreach($tree as $tag => $customer){
    foreach($customer as $customerId => $order){
        echo "{\"name\":\"".$customerId."\",";
        echo "\"children\": ["."
";
            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.

As someone already said, don't try to build manually a JSON string, build a data structure in php and use 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);