Ale*_*lov 7 php arrays recursion merge
我需要以某种不同的方式合并一些数组,并使用array_merge_recursive.然而,我需要改变一些东西,我不知道如何改变.这是来自php.net的引用
但是,如果数组具有相同的数字键,则后面的值不会覆盖原始值,但会附加.
我想要这个值,不要追加,我不想在新数组中追加精确的值.希望你能理解这一点.
例:
$array = array(
'some' => array(
'other' => 'key',
),
);
$array2 = array();
$array2['some']['other'] = 'key2';
Run Code Online (Sandbox Code Playgroud)
如果我使用array_merge_recursive它将导致:
Array (
[some] => Array
(
[other] => Array
(
[0] => key
[1] => key2
)
) )
Run Code Online (Sandbox Code Playgroud)
我想如果它匹配相同的结果,而不是追加它.我知道,你会说,然后使用array_merge,但它也不能很好地工作.如果我用这个:
$array = array(
'some' => array(
'other' => 'key',
),
);
$array2 = array();
$array2['some']['other2'] = 'key2';
print_r(array_merge($array, $array2));
Run Code Online (Sandbox Code Playgroud)
它将从列表中删除$ array [some] [other]并仅留下$ array [some] [other2].我不知道哪个更好,因为没有人让它更好.
试试这个
<?php
function mymerge(&$a,$b){ //$a will be result. $a will be edited. It's to avoid a lot of copying in recursion
foreach($b as $child=>$value){
if(isset($a[$child])){
if(is_array($a[$child]) && is_array($value)){ //merge if they are both arrays
mymerge($a[$child],$value);
}
//else ignore, you can add your own logic, i.e when 1 of them is array
}
else
$a[$child]=$value; //add if not exists
}
//return $a;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3998 次 |
最近记录: |