gpt4 book ai didi

php - 如何使用 PHP 在 JSON 中添加数据

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:56:26 25 4
gpt4 key购买 nike

我有一个具有以下语法的 json 文件:

[
{
"fields": {
"service_number": "service_number",
"physical_address": "physical_address",
"account_id": "account_id",
"contact_id": "contact_id"
},
"someId": "asd23f",
"status": "Active",
"perCode": "1",
"idCode": "0987",
"nextCode": "09"
},
{
"fields": {
"service_number": "service_number",
"physical_address": "physical_address",
"account_id": "account_id",
"contact_id": "contact_id"
},
"someId": "789096",
"status": "Active",
"perCode": "1",
"idCode": "076543",
"nextCode": "09"
}
]

我想使用 for 循环在 nextCode 之前或之后添加类似 userID 的内容。有什么解决办法吗?到目前为止,我试过这个:

$data = json_decode($file, true);
foreach ($data as $key => $val)
{
foreach ($val as $key=>$c)
{
if (is_array($c))
continue;
$data .= $data . "user_id:$userId";
}
}

当然这并不能解决问题,请问有什么想法吗?

最佳答案

有几个问题。

  • 首先,foreach 循环使用它迭代的数组副本,因此修改其中的一项不会更改原始数组。

  • 然后,您的内部 foreach 循环会覆盖外部循环中的 $key。那导致问题,但这没关系,因为您实际上不需要内部循环。

  • 最后,在解码 JSON 字符串后,$data 将是一个数组,因此用 .= 附加到它不会起作用,即使这样做了,您也只是在它的末尾粘贴一些东西,而不是在循环所在的特定点。

只需引用您需要的特定键并在那里设置值即可。

$data = json_decode($file, true);
foreach ($data as $key => $val)
{
$data[$key]['user_id'] = $userId;
}
$data = json_encode($data);

关于php - 如何使用 PHP 在 JSON 中添加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51955482/

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