duanjiaolia97750 2016-11-28 15:47
浏览 46
已采纳

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

This question already has an answer here:

This is my sample.json file

  "general": {
    "option_name" : "option_name",
    "filter_name" : "filter name"
}

and I want to update the value using key

$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);

Here I want to assign Array

 [0] => general
 [1] => filter_name

should be

$data['general']['filter_name']

How to define array like this? Thanks

</div>
  • 写回答

1条回答 默认 最新

  • douminfu8033 2016-11-28 16:07
    关注

    You can do it using references:

    $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);
    

    How it works:

    1. Create a reference for your array: $ref = &$json;
    2. Iterate through $path items to get value of $json['general']['filter_name']:
      1. On the first iteration $ref will be reference to $json['general']
      2. On the second iteration $ref will be reference to $json['general']['filter_name'] - that's exactly what we want
    3. When assign $ref = "new filtername"; you're assigning $json['general']['filter_name'] = "new filtername";
    4. Don't forget to remove reference unset($ref);, without doing it there is possibility to change $ref and thus to change $json['general']['filter_name']
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog