我正在拉入一个 json 文件,并将一个嵌套节点值更改为一个用 | 分隔的值。然后编码并保存文件。
如何使用 php 实现此目的?
我的 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" }
]
}
]
}
这就是我所拥有的
file_put_contents("importfiles/importproducts1.json", $response);
//tweak output
$json_object = file_get_contents('importfiles/importproducts1.json');
$data = json_decode($json_object, true);
$data['some_key'] = "some_value"; //What goes here ?
$json_object = json_encode($data);
file_put_contents('importfiles/importproducts.json', $json_object);
循环
list
,对于每个项目,用一个新数组覆盖 Attribute Grommets
数组,将第一个 Id 放入其中,并使用 array_column
从完整数组中提取标题,并使用所需的分隔符进行内爆。
foreach($data['list'] as $key => $item) {
$data['list'][$key]['Attribute Grommets'] = [
[
'Id' => $item['Attribute Grommets'][0]['Id'],
'Title' => implode(' | ', array_column($item['Attribute Grommets'], 'Title'))
]
];
}