You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP修改嵌套JSON节点并重新编码保存文件

解决JSON中嵌套节点Title合并问题

需求说明:读取JSON文件,将其中嵌套节点Attribute Grommets下的多个Title值合并为用|分隔的单个值,重新编码为JSON后保存。

原始JSON结构:

{
    "list": [
        {
            "Id": 398,
            "Product Title": "Banner",
            "Sku": "vb-13oz",
            "Short Description": "text",
            "Long Description": "text",
            "Cost": "0.95",
            "Price": "3.25",
            "Category": [{ "Id": 9, "Title": "Banners" }],
            "Attribute Sides": [{ "Id": 1, "Title": "1 Side" }],
            "Attribute Grommets": [
                { "Id": 1, "Title": "Every 2' All Sides" },
                { "Id": 2, "Title": "Every 2' Top and Bottom" },
                { "Id": 3, "Title": "Every 2' Left & Right" },
                { "Id": 4, "Title": "4 Corners Only" },
                { "Id": 5, "Title": "No Gromments" }
            ]
        }
    ]
}

期望输出结果:

{
    "list": [
        {
            "Id": 398,
            "Product Title": "Banner",
            "Sku": "vb-13oz",
            "Short Description": "text",
            "Long Description": "text",
            "Cost": "0.95",
            "Price": "3.25",
            "Category": [{ "Id": 9, "Title": "Banners" }],
            "Attribute Sides": [{ "Id": 1, "Title": "1 Side" }],
            "Attribute Grommets": [
                 { "Id": 1, "Title": "Every 2' All Sides | Every 2' Top and Bottom | Every 2' Left & Right | 4 Corners Only | No Gromments" }
            ]
        }
    ]
}

修改后的PHP代码:

file_put_contents("importfiles/importproducts1.json", $response);

// 处理JSON数据
$json_object = file_get_contents('importfiles/importproducts1.json');
$data = json_decode($json_object, true);

// 遍历list中的每个产品
foreach ($data['list'] as &$product) {
    // 检查当前产品是否包含Attribute Grommets节点
    if (isset($product['Attribute Grommets']) && is_array($product['Attribute Grommets'])) {
        // 提取所有Title值并合并成|分隔的字符串
        $titles = array_column($product['Attribute Grommets'], 'Title');
        $mergedTitle = implode(' | ', $titles);
        
        // 替换原Attribute Grommets为合并后的结构
        $product['Attribute Grommets'] = [
            [
                'Id' => 1, // 若需要保留原第一个元素的Id,可改为$product['Attribute Grommets'][0]['Id']
                'Title' => $mergedTitle
            ]
        ];
    }
}
unset($product); // 解除引用,避免后续意外修改

$json_object = json_encode($data, JSON_PRETTY_PRINT); // 格式化输出,可选
file_put_contents('importfiles/importproducts.json', $json_object);

代码说明:

  • 用foreach遍历list中的每个产品,通过引用直接修改原数据
  • array_column快速提取Attribute Grommets下所有Title值
  • implode用|连接所有Title字符串
  • 替换原Attribute Grommets为包含合并后Title的数组结构,Id可根据需求选择固定值或保留原第一个元素的Id
  • 可选使用JSON_PRETTY_PRINT参数让输出的JSON格式更清晰

内容的提问来源于stack exchange,提问作者Riots

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 12:52:30