这是我的sample.json文件
"general": {
"option_name" : "option_name",
"filter_name" : "filter name"
}
我想用密钥
更新值$string = "general.filter_name";
$updateContent = "new filtername";
$langArray = explode('.',$string);
print_r($langArray);
/*Array
(
[0] => general
[1] => filter_name
) */
$file='assets/sample.json';
$jsonString = file_get_contents($file);
$data = json_decode($jsonString, true);
**$data['general']['filter_name'] = $updateContent; **
$newJsonString = json_encode($data);
file_put_contents($file, $newJsonString);
这里我想分配数组
[0] => general
[1] => filter_name
应该是
$data['general']['filter_name']
如何定义这样的数组?感谢
答案 0 :(得分:1)
你可以使用引用来做到这一点:
$json = file_get_contents('assets/sample.json');
$json = json_decode($json, true);
$path = "general.filter_name";
$path = explode('.', $path);
$ref = &$json;
foreach ($path as $key) {
$ref = &$ref[$key];
}
$ref = "new filtername";
unset($ref);
工作原理:
$ref = &$json;
$path
项以获取$json['general']['filter_name']
的值:
$ref
将引用$json['general']
$ref
上将引用$json['general']['filter_name']
- 这正是我们想要的$ref = "new filtername";
时,您需要分配$json['general']['filter_name'] = "new filtername";
unset($ref);
,如果不这样做,就有可能更改$ref
,从而更改$json['general']['filter_name']