PHP执行改变数组格式



我的php文件,接收两个变量$addNodeProperty$addNodeValue,并将它们添加到数组中。不幸的是,在这个过程中格式发生了变化,我不知道为什么。

数组,之前PHP的执行:

"properties": [
{
"property": "CPU",
"value": "4"
},
{
"property": "RAM",
"value": "16 GB"
},
{
"property": "HDD",
"value": "2 TB"
}
]

数组,之后的PHP的执行。您将注意到前三个条目前面的对象编号。那些我需要删除的,它应该看起来像执行前的数组,添加了对象:

"properties": {
"0": {
"property": "CPU",
"value": "4"
},
"1": {
"property": "RAM",
"value": "16 GB"
},
"2": {
"property": "HDD",
"value": "2 TB"
},
{
"property": "Neue Eigenschaft",
"value": "Neuer Wert"
}
}

我正在使用的php:

<?php
header("Access-Control-Allow-Origin: *");
$nodeId = ($_POST['nodeId']);
$addNodeProperty = ($_POST['addNodeProperty']);
$addNodeValue = ($_POST['addNodeValue']);
$json = file_get_contents("../data/data.json");
$data = json_decode($json, true);
$nodes = $data['nodes'];
$nodeIdInArray = array_search($nodeId, array_column($nodes, 'id'));
$nodes[$nodeIdInArray]['properties']['property'] = $addNodeProperty;
$nodes[$nodeIdInArray]['properties']['value'] = $addNodeValue;
$nodes = array_values($nodes);
$data['nodes'] = $nodes;
$json = json_encode($data);
file_put_contents("../data/data.json", $json);
?>

简单数组不能保存键,这就是为什么它被转换为关联数组。

如果你仍然需要像第一个代码

"properties": [
{
"property": "CPU",
"value": "4"
},
{
"property": "RAM",
"value": "16 GB"
},
{
"property": "HDD",
"value": "2 TB"
}
]

那么你应该这样写:

... ['properties'][] = ["property"=> "Neue Eigenschaft", "value"=> "Neuer Wert"]

最新更新