我们假设我有一个如下数组:
$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,依此类推......
答案 0 :(得分:1)
这是动态设置功能,你可以使用它设置任何深度。 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;
}
答案 1 :(得分:0)
$settings = array(
"age" => "25",
"data" => array(
"name" => "John Dewey",
"zip_code" => "00000"
)
);
$new_value = "Micheal";
$settings["data"]["name"] = $new_value;
print_r($settings);
答案 2 :(得分:0)
//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;
}