【问题标题】:Dynamically modify associative array values in php [duplicate]动态修改php中的关联数组值[重复]
【发布时间】:2023-03-21 21:19:01
【问题描述】:

假设我有一个如下数组:

$settings = array(
    "age" => "25",
    "data" => array(
            "name" => "John Dewey",
            "zip_code" => "00000"
        )
);

这是我的意见:

$target_directory = "data.name";    // targets $settings["data"]["name"]
$new_value = "Micheal";    // I want to change 
                           // $settings["data"]["name"] with this value

我想要类似于以下内容:

$new_array = dont_know_what_to_do($target_directory, $new_value, $settings);

print_r($new_array) 应返回以下内容:

Array
(
    [age] => 25
    [data] => Array
        (
            [name] => Micheal,
            "zip_code" => "00000"
        )

)

更改应该是完全动态的,这意味着data.zip_code = "98985" 也应该仅将邮政编码值从 00000 更改为 98985,等等...

【问题讨论】:

  • 你试过的代码在哪里?
  • 我试图爆炸(".", $target_directory);但我不知道下一步该做什么?
  • 只更新数据中的键?
  • 试试我的答案。如果有效
  • 你的意思是,“只有数据键被更新?”?如果是这样……那么是的。但是,如果我再向下一棵树,假设 data.name.first_name = $new_value。那么它应该只改变 ["data"]["name"]["first_name"] = $new_value;

标签: php arrays recursion


【解决方案1】:
$settings = array(
    "age" => "25",
    "data" => array(
            "name" => "John Dewey",
            "zip_code" => "00000"
        )
);
$new_value = "Micheal"; 
$settings["data"]["name"] = $new_value;
print_r($settings);

【讨论】:

  • 它必须是完全动态的。您使用了一些静态方法。请像这样定位 data.name 是需要的。介意复习一下这个问题吗?并希望给出答案?
  • data.name 的意思是......数据是一个 javascript 对象,对吗?
  • 是的,有点……我希望它像 Javascript 定位一样工作,但在 php 中。
【解决方案2】:
//In your main function
public function something() {
    $settings = array(
     "age" => "25",
     "data" => array(
        "name" => "John Dewey",
        "zip_code" => "00000"
      )
    );

   $target = 'data.name';
   $input = 'Other Name'

  $new_arr = dont_know_what_to_do($target_dir, $input);

  print_r($new_arr);        
}


//Create new function
public function dont_know_what_to_do($settings, $target, $input) {
  $key = explode('.', $target)
  return $settings['data'][$key[1]] = $input;
}

【讨论】:

  • 会起作用,但如果我再往下走,假设 data.name.first_name = $new_value。那么它应该只改变 ["data"]["name"]["first_name"] = $new_value;
【解决方案3】:

这里是动态设置功能,你可以用它设置任意深度。 Demo here 你的问题。

function set($settings, $target_directory, $new_value)
{
  $array = explode('.', $target_directory);
  $ref = &$settings;
  while($v = current($array))
  {
    $ref = &$ref[$v];
    next($array);
  }
  $ref = $new_value;
  return $settings;
}

【讨论】:

  • 哦!我从来不知道的那个&标志......做到了这一切。非常感谢你。学到了一些新的但很重要的东西。
  • @ArifBillah for php & 操作员参考stackoverflow.com/questions/3737139/…
  • 信息量很大。将不得不学习相当长的时间。再次感谢您。
猜你喜欢
  • 2017-06-17
  • 2013-09-13
  • 1970-01-01
  • 2021-03-14
  • 1970-01-01
  • 1970-01-01
  • 2017-10-26
  • 1970-01-01
  • 2015-07-23
相关资源
最近更新 更多