php - 将数据添加到 JSON 子数组
问题描述
这是我的 JSON 文件(database.json):
{
"doctors": [
{
"ID": "ahmadakhavan",
"pass": "1234",
"name": "Ahmad Akhavan",
"profilePic": "address",
},
{
"ID": "akramparand",
"pass": "1234",
"name": "Akram Parand",
"profilePic": "address",
}
],
"games": [
{
"ID": "shuttlefuel_1",
"locked": "0",
"logo": "gameLogo",
},
{
"ID": "birthdaycake",
"locked": "0",
"logo": "gameLogo",
}
],
"users": [
{
"ID": "alirezapir",
"prescribes": [
{
"doctorName": "doctor1",
"done": "yes",
"gameId": "wordschain"
},
{
"doctorName": "doctor2",
"done": "no",
"gameId": "numberlab"
}
],
"profilePic": "address"
},
{
"ID": "amirdibaei",
"pass": "1234",
"profilePic": "address"
}
]
}
我想在prescribes
特定 ID 的数组下添加一个子项。
下面是我在我的 PHP 代码中所做的:
<?php
$username = $_REQUEST['name'];
$data = $_REQUEST['data'];
//Load the file
$contents = file_get_contents('./database.json');
$arraydata = json_decode($data,true);
//Decode the JSON data into a PHP array.
$contentsDecoded = json_decode($contents, true );
foreach($contentsDecoded['users'] as $item){
if($item['ID'] == $username){
if(!isset($item['prescribes'])){
$item['prescribes'] = Array();
}
array_push($item['prescribes'],$arraydata);
$json = json_encode($contentsDecoded, JSON_UNESCAPED_UNICODE );
file_put_contents('./database.json', $json);
exit('1');
exit;
}
}
exit('0');
exit;
?>
如果我$item['prescribes']
在该行之后回显,array_push($item['prescribes'],$arraydata);
我会看到添加了数据,但原始文件 ( database.json
) 不会显示新添加的数据。
(意味着这个新数据不会添加到$contentsDecoded
)
解决方案
您必须更改foreach()
如下代码:-
foreach($contentsDecoded['users'] as &$item){ //& used as call by reference
if($item['ID'] == $username){
$item['prescribes'][] = $arraydata; //assign new value directly
$json = json_encode($contentsDecoded, JSON_UNESCAPED_UNICODE );
file_put_contents('./database.json', $json);
exit;
}
}
推荐阅读
- java - 关于约束布局的问题
- mongodb - 如何使用用户管理方法和 pymongo 在 MongoDB 中通过 UserId 查询用户
- hibernate - 有没有办法在 JPA/Hibernate 的 java doc 中包含 db 列名?
- html - 本地主机上的 iframe 标记和烧瓶项目的本地 html 文件中没有内容(在 mac 上的 vs 代码中)
- user-interface - 如何使用空手道 UI 向右/向左滚动?
- firebase - 很少有 Android 的 app_update 事件
- php - 如何显示像 1.1k 而不是 1100 这样的数字
- javascript - 使 React 与 math.js 库一起工作
- python - 如何在字典中的枚举中添加文档字符串
- c# - 如何使用 DeserializeObject 方法处理空值