我的问题是通过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-Content:
[
{
"server": {
"TEST": [
{
"svc": "TEST",
"id": 1
}
]
}
}
]
但我需要这个:
{
"server": {
"TESTSERVER": [
{"svc":"TESTSERVICE", "id":1}
]
}
}
我知道[]用于数组,而{}用于对象。我首先需要一个JSON-Object - >服务器,然后是第二个JSON-Object - > hostname,然后是一个JSON-Array,后面是几个填充了Servicenames和ID的JSON-Objects。
我希望,你可以帮助我,因为这个问题让我现在变得疯狂。