如何在保留所有唯一键/值的同时合并多维数组? [英] how to merge multidimensional arrays whilst preserving all unique key/values?
本文介绍了如何在保留所有唯一键/值的同时合并多维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有内置的php函数,或者我必须编写自己的函数以合并两个这样的多维数组
is there are in build php function or I have to write my own one to merge two multidimensional arrays like that
$list1 = array("school1" => array('string1','string2'));
$list2 = array("school1" => array('string1','string3'),
"school2" => array('string1','string4','string5')
);
插入数组,其中什么都不会被覆盖或省略.我想在第二个数组"中只有唯一的值.这意味着数组school1
仅包含一次字符串string1
into array where nothing will be overwritten or omitted. I want to have only unique values in the the 'second array'. Meaning that array school1
will contain string string1
once only
Array ( [school1] => Array ( [0] => string3 [1] => string2 [2] => string1 )
[school2] => Array ( [0] => string5 [1] => string4 [2] => string1 ) )
理想的情况是,如果我可以拥有第二个数组= string1,string2 ....排序的desc
ideal would be if I can have the second array = string1, string2 .... sorted desc
推荐答案
我的解决方案
function merge_db_lists ($list1, $list2) {
$final_array = array();
$final_array = go_through_list($list1, $final_array);
$final_array = go_through_list($list2, $final_array);
return $final_array;
}
function go_through_list($list,$output){
foreach (array_keys($list) as $key){
if (array_key_exists($key, $output)){
foreach ($list[$key] as $item ){
$output[$key][] = $item;
}
arsort($output[$key]);
}
else{
$output[$key] = $list[$key];
}
}
return $output;
}
这篇关于如何在保留所有唯一键/值的同时合并多维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文