gpt4 book ai didi

php - 使用 PHP 重命名 JSON 子项

转载 作者:行者123 更新时间:2023-12-04 14:45:54 25 4
gpt4 key购买 nike

我正在尝试帮助现有项目中的 JSON 结构格式,目标是重命名一些子项而不是值。像这样的JSON格式

{
"table-name": "Kiwi",
"created-on": "November 20, 2021",
"token": "lsUVozOB2TxhvMv",
"icons": "default",
"links": "default",
"extra": "default",
"mode": "Private",
"collaborators": [],
"columns": {
"Name": {
"type": "text",
"extra": ""
},
"Info": {
"type": "longtext",
"extra": ""
},
"Status": {
"type": "droplist",
"extra": {
"fr": "Pending",
"sc": "On-going",
"th": "Completed",
"fo": "Cancelled"
}
}
},
"data": [{
"Name": "Team Reports",
"Info": "Submitting marketing materials reports",
"Status": "Completed"
},
{
"Name": "Fabia HR",
"Info": "Brian asking for a report",
"Status": "Pending"
},
{
"Name": "Fabia",
"Info": "Meeting with CEO @cafe 9:00",
"Status": "Cancelled"
}
]
}

我们正在研究,将Name重命名为Task,同时保留另一个。使用 array push 和 slice 键后,我得到 0 作为键和“Task as subkeys like

"0":{
"Task":{
"type":"text",
"extra":""
},

代码如下所示。请在空闲时间分享您的解决方案,在此先感谢您,非常感谢您的关注。完全菜鸟在这里🖐PHP:

$file = file.json;  
$jsn = file_get_contents($file);
$data = json_decode($jsn, true);

//get name data array
$sub_data = $data['columns']['Name'];

$new_rename = array(
"Task" => $sub_data;
);

array_push($data['columns'],$new_rename);

//now delete old "Name";
array_slice($data['columns'],'Name')

//save stuff
$jsn = json_encode($data);
file_put_contents($file,$jsn);

最佳答案

鉴于您正在使用 JSON 对象,因此是 PHP 关联数组(与数字索引相反),您真正需要做的就是设置新属性并取消设置旧属性

$data["columns"]["Task"] = $data["columns"]["Name"];
unset($data["columns"]["Name"]);

演示~ https://3v4l.org/7pBpZ

关于php - 使用 PHP 重命名 JSON 子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70061320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com