php - 将对象推送到 JSON 文件
问题描述
我的问题是通过 PHP 以正确的方式将一些内容推送到 JSON 文件。我已经写了一些代码,但它不会工作。
这是我的代码:
//Get Form Data
$formdata_host = array (
'server' => array ( $Server => array(
array (
'svc' => $_POST['valservice'],
'id'=> 1
)
))
);
//Get data from existing json file
$jsondata = file_get_contents($filename_moni);
//converts json data into array
$arr_data = json_decode($jsondata, true);
//Push details data to array
array_push($arr_data,$formdata_host);
//Reindex the Array
$arr_data = array_values($arr_data);
//Convert updated array to JSON
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT|JSON_NUMERIC_CHECK);
//write json data into data.json file
if(file_put_contents($filename_moni, $jsondata)) {
echo 'Daten erfolgreich gespeichert!';
}
else
echo "Error";
}
catch (Exception $e) {
echo 'Ausnahme entdeckt: ', $e->getMessage(), "\n";
}
这是我执行后得到的 JSON 内容:
[
{
"server": {
"TEST": [
{
"svc": "TEST",
"id": 1
}
]
}
}
]
但我需要这个:
{
"server": {
"TESTSERVER": [
{"svc":"TESTSERVICE", "id":1}
]
}
}
我知道 [] 用于数组,而 {} 用于对象。我首先需要一个 JSON-Object -> 服务器,然后是第二个 JSON-Object -> 主机名,然后是一个 JSON-Array,后面是几个填充了服务名和 ID 的 JSON-Object。
我希望你能帮助我,因为这个问题现在让我发疯。
解决方案
改变这两件事(正如我在评论中所说)
//Push details data to array
$arr_data = array_merge($arr_data,$formdata_host);
//array_push($arr_data,$formdata_host);
//Reindex the Array
//$arr_data = array_values($arr_data);
这会将server
密钥放在您想要的数组的顶层。
输出
{
"server": {
"TESTSERVER": [
{
"svc": "TESTSERVER",
"id": 1
}
]
}
}
我可以说array_values
是错误的,因为您想server
成为“顶级”键,而这永远不会发生,array_values
因为它会剥离该键。
并且array_push
在组合数组时很少需要这样做,因为它会推动数组的整个结构。所以你有了
[ "server" => ..... ]
被添加,而不仅仅是
"server" => .....
内容。
推荐阅读
- python - Linregress 输出似乎不正确
- sql-server - 将两个查询的结果相除,在第三个查询中得到结果
- python - 如何检测 pygame 中 Sprite 类的 2 个表面对象之间的碰撞?
- python - 每个客户提供不同样本大小的样本
- python - 如何安装 spacy 并避免 32/64 位错误?
- java - 从自定义适配器获取片段中的 UI 元素 ID
- javascript - 如何使用 Webpack 构建 React 应用程序并导入资产文件夹?
- c++ - 使用 OpenCV 计数硬币
- python - 如何修复 OSError:[WinError 6] 句柄对 Python 和 Selenium 无效?
- google-apps-script - 如何获取活动用户并放置在特定单元格中?