2 回答

TA貢獻(xiàn)1794條經(jīng)驗 獲得超8個贊
您可能必須編寫自己的函數(shù),以您認(rèn)為合適的方式進(jìn)行替換。我認(rèn)為應(yīng)該:
接受兩個數(shù)組 ($a,$b) 作為參數(shù)
如果 $a[KEY] 是一個數(shù)組且 $b[KEY] 未設(shè)置,則保留 $a[KEY]
如果 $a[KEY] 是一個數(shù)組并且 $b[KEY] 是一個數(shù)組,調(diào)用這個方法 w/ ($a[KEY] & $b[KEY])
如果 $a 的子節(jié)點不是數(shù)組且 $b 有子節(jié)點,則將 $a 替換為 $b
或者類似的東西......我很難概念化你到底需要什么,并為它編寫一個函數(shù),我意識到有些極端情況可能會出現(xiàn)在更復(fù)雜的數(shù)組中。
所以我寫了這個函數(shù)和測試。我只使用您提供的示例數(shù)組對其進(jìn)行了測試,但它提供了正確的輸出。如果您向數(shù)組添加另一層,或者其中有一個數(shù)組,其中有一些是數(shù)組的孩子和一些不是數(shù)組的孩子,這可能會出現(xiàn)問題。
<?php
function 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);

TA貢獻(xiàn)1851條經(jīng)驗 獲得超5個贊
蘆葦,
謝謝你這對我有用..但我從你的代碼中得到啟發(fā)并開始改進(jìn)它。對于其他需要這樣的人:
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));
結(jié)果:
[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
- 2 回答
- 0 關(guān)注
- 126 瀏覽
添加回答
舉報