我在 php 中有一个多维数组,我想根据一些规则对其进行操作。
输入数组:( 以 JSON 形式打印的变量)
[
{
"meta":{
"title": "Adressdata",
"name": "adress"
},
"data":{
"desc":{ "tooltip": "text",
"maxlength": "100"
},
"line1":{ "tooltip": "Recipient",
"maxlength": "40"
}
}
]
规则:
{
"0>meta>title": "Companyaddress",
"0>data>desc": {
"tooltip": "Another Text",
"maxLength": "150"
}
}
(有两条规则,索引说明输入数组中的哪个字段必须更改,值包含要插入的数据。注意第二条规则要插入一个对象)
问题:
我想根据规则更改输入数组的内容,但我很难做到这一点。
这是我已经拥有的 php 代码:
<?php
$input = json_decode(file_get_contents("inputData.json"),true);
$rules = json_decode(file_get_contents("rules.json"),true);
foreach ($rules as $target => $replacement) {
//rule: "0>meta>title": "newTitle"
$node = $input;
foreach (explode(">",$target) as $index) {
$node = $node[$index];
}
$node = $replacement; //replace doesn't work
}
echo "Result-Array: ";
print_r($input);
?>
一切正常,除了我无法更改值。为什么?因为每次我设置 $node-Variable 时,我都会创建一个新变量。而且我只修改了$node的内容,没有修改$input的内容。
所以我尝试使用引用- 这也不起作用:当我将 2 $node-Lines 更改为此代码时:
$node = &$input;
[...]
$node = &$node[$keys[$i]]; //go to child-node
但这不起作用,因为我只想导航到子节点的第二行更改了父元素(因为 $node 是参考)。
我不知道是否有这样做的技巧,我希望有人可以帮助我