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

我有这个脚本构造一个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中的所有逗号,而不是最后一个。

问候。

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


正如有人已经说过,不要尝试手动构建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/47287.html

上一篇: Remove last comma from JSON constructed with foreach loop

下一篇: Pretty printing JSON isn't working