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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀