幕布斯7119047
您可能必须编写自己的函数,以您认为合适的方式进行替换。我认为应该:接受两个数组 ($a,$b) 作为参数如果 $a[KEY] 是一个数组且 $b[KEY] 未设置,则保留 $a[KEY]如果 $a[KEY] 是一个数组并且 $b[KEY] 是一个数组,调用这个方法 w/ ($a[KEY] & $b[KEY])如果 $a 的子节点不是数组且 $b 有子节点,则将 $a 替换为 $b或者类似的东西......我很难概念化你到底需要什么,并为它编写一个函数,我意识到有些极端情况可能会出现在更复杂的数组中。所以我写了这个函数和测试。我只使用您提供的示例数组对其进行了测试,但它提供了正确的输出。如果您向数组添加另一层,或者其中有一个数组,其中有一些是数组的孩子和一些不是数组的孩子,这可能会出现问题。<?phpfunction recurseReplace($a,$b){ $ret = []; foreach ($a as $key=>$value){ if (!isset($b[$key])&&is_array($value)){ $ret[$key] = $value; continue; } if (is_array($value)&&isset($b[$key])&&is_array($b[$key])){ $ret[$key] = recurseReplace($value,$b[$key]); continue; } } if (count($ret)==0){ foreach ($b as $key=>$value){ $ret[$key] = $value; } } return $ret;}$a = [ "test" => [ "me"=>['test','me','now'], "me2"=>["test",'me','now'] ] ];$b = [ "test" => [ "me2"=>["name"=>'firstname',"last"=>"lastname"] ] ];$desired = [ "test" => [ "me"=>['test','me','now'], "me2"=>["name"=>'firstname',"last"=>"lastname"] ] ];$final = recurseReplace($a,$b);echo "\n\n-----final output::---\n\n";print_r($final);echo "\n\n-----desired::---\n\n";print_r($desired);
江户川乱折腾
芦苇,谢谢你这对我有用..但我从你的代码中得到启发并开始改进它。对于其他需要这样的人: function conf_get($paths, $array) { $paths = !is_array($paths) ? [] : $paths; foreach ($paths as $path) $array = $array[$path]; return $array; } function conf_set($paths, $value, $array) { $array = !is_array($array) ? [] : $paths; // Initialize array if $array not set $result = &$array; foreach ($paths as $i => $path) { if ($i < count($paths) - 1) { if (!isset($result[$path])) $result[$path] = []; $result = &$result[$path]; } else $result[$path] = $value; } return $result; } $config = []; $config ['test']['me'] = ['test', 'me', 'now']; $config ['test']['me2'] = ['test', 'me', 'now'];echo "\n INITIAL CONFIG"; print_r($config );echo "\n GET PATH test"; print_r(conf_get('test', $config));echo "\n GET PATH test,me1" ;print_r(conf_get(['test', 'me2'], $config);echo "\n REPLACE PATH test,me2 with new array" ;print_r(conf_set(['test', 'me2'], ['name' => 'firstname', 'last' => 'lastname'], $config), "");echo "\n ADD PATH test,me6 with new array";print_r(conf_set(['test', 'me6'], ['name' => 'firstname', 'last' => 'lastname'], $config));结果:[INITIAL CONFIG] [test] => Array [me] => Array [0] => test [1] => me [2] => now [me2] => Array [0] => test [1] => me [2] => now[GET PATH test] [test] => Array [me] => Array [0] => test [1] => me [2] => now [me2] => Array [0] => test [1] => me [2] => now[GET PATH test,me1] [0] => test [1] => me [2] => now[REPLACE PATH test,me2 with new array] [me2] => Array [name] => firstname [last] => lastname[ADD PATH test,me6 with new array] [me6] => Array [name] => firstname [last] => lastname