首页 > 解决方案 > 将对象推送到 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。

我希望你能帮助我,因为这个问题现在让我发疯。

标签: phparraysjsonfileobject

解决方案


改变这两件事(正如我在评论中所说)

//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" => .....

内容。


推荐阅读