如何在PHP中使用explode值分配数组变量?

时间:2016-11-28 15:47:44

标签: php arrays

这是我的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']

如何定义这样的数组?感谢

1 个答案:

答案 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);

工作原理:

  1. 为您的阵列创建参考:$ref = &$json;
  2. 遍历$path项以获取$json['general']['filter_name']的值:
    1. 在第一次迭代$ref将引用$json['general']
    2. 在第二次迭代$ref上将引用$json['general']['filter_name'] - 这正是我们想要的
  3. 分配$ref = "new filtername";时,您需要分配$json['general']['filter_name'] = "new filtername";
  4. 不要忘记删除引用unset($ref);,如果不这样做,就有可能更改$ref,从而更改$json['general']['filter_name']