将对象推送到JSON文件

时间:2018-09-17 15:18:57

标签: php arrays json file object

我的问题是通过PHP以正确的方式将一些Content推送到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。

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

2 个答案:

答案 0 :(得分:0)

更改这2件事(正如我在评论中所说)

//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
            }
        ]
    }
}

Sandbox

我可以判断array_values是错误的,因为您希望server是“顶级”密钥,array_values永远不会发生,因为它将剥离该密钥。

array_push很少是组合数组时想要执行的操作,因为它可以推动数组的整个结构。所以你有

 [ "server" => ..... ]

被添加,而不只是

"server" => .....

内容。

答案 1 :(得分:0)

我找到了解决方法:

array_replace_recursive($array, $array2);

来源: php array_merge without erasing values?