我有一个带有 JSON 对象的 JSON 文件,我正在尝试使用 PHP 读取和编辑,但我想更改特定的 Key 值,这被证明是一个问题。任何人都会有任何他们可能知道的可能有帮助的指针或链接吗?
谢谢
你可以试试这个。
首先,解码您的 JSON:
$json_object = file_get_contents('some_file_name.json');
$data = json_decode($json_object, true);
然后编辑您想要的内容,例如:
$data['some_key'] = "some_value";
最后将其重写回文件(或更新的文件):
$json_object = json_encode($data);
file_put_contents('some_file_name.json', $json_object);
注意:我假设 JSON 来自一个文件,但是代替该文件系统函数,您可以很好地使用任何返回 JSON 对象的东西。
如果您有嵌套键,则可以执行以下操作:
1. 将 JSON 解码为 PHP 数组
$arrayData = json_decode($jsonData, true);
2.递归指定替换
$replacementData = array('a' => array('b' => 'random2'), 'c' => 'abc');
例如,这将用random2b替换 key内 key的值,并将root 级别中的 key 值替换为abc。ac
3.递归执行替换
$newArrayData = array_replace_recursive($arrayData, $replacementData);
4.编码新的JSON
$newJsonData = json_encode($newArrayData);
测试代码
echo print_r(array_replace_recursive(array('a' => array('b' => 'random'), 'c' => 'def'), array('a' => array('b' => 'random2'), 'c' => 'abc')), true);
应该用random2替换b内部a值random ,用abc替换值def并输出:c
Array(
[a] => Array
(
[b] => random2
)
[c] => abc
)
将 json 转换为数组并递归更新键 (depth-nth)
function json_overwrite($json_original, $json_overwrite)
{
$original = json_decode($json_original, true);
$overwrite = json_decode($json_overwrite, true);
$original = array_overwrite($original, $overwrite);
return json_encode($original);
}
递归迭代和替换 $original
function array_overwrite(&$original, $overwrite)
{
// Not included in function signature so we can return silently if not an array
if (!is_array($overwrite)) {
return;
}
if (!is_array($original)) {
$original = $overwrite;
}
foreach($overwrite as $key => $value) {
if (array_key_exists($key, $original) && is_array($value)) {
array_overwrite($original[$key], $overwrite[$key]);
} else {
$original[$key] = $value;
}
}
return $original;
}
快速测试
$json1 = '{"hello": 1, "hello2": {"come": "here!", "you": 2} }';
$json2 = '{"hello": 2, "hello2": {"come": "here!", "you": 3} }';
var_dump(json_overwrite($json1, $json2));