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']
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改