问题描述
所以,我的工作,结合四组小PHP应用程序。
现在有一些可能的阵列将是无效的可能性。
我尝试以下解决方案,以独特的合并四个阵列。
So i'm working on a small php applications that combines four arrays.Now there is a possibility that some of the possible arrays will be null.I tried the following solution to merge the four arrays uniquely.
<?php
$a = [1,2,3,4,5];
$b = null;
$c = [5,4,3,2,1];
$d = [1,2];
$new_array;
if(is_array($a) && is_array($b) && is_array($c) && is_array($d))
{
$new_array = array_unique(array_merge($a,$b,$c,$d));
}else if(is_array($a) && is_array($b) && is_array($c))
{
$new_array = array_unique(array_merge($a,$b,$c));
}else if(is_array($a) && is_array($b))
{
$new_array = array_unique(array_merge($a,$b));
}else{
$new_array = $a;
}
print_r($new_array);
?>
我很快意识到我的code是,虽然不包括空变量并不满足阵列的所有可能的组合非常不正常的。
I soon realized my code was highly dysfunctional in that it does not cater for all possible combinations of arrays while excluding the null variables.
我该如何解决这个问题。确保所有属于数组变量被合并一个第二那些没有被丢弃。
谢谢
How do I solve this. Ensuring that all the variables that are arrays are merged a nd those that are not are discarded.Thanks
推荐答案
这个怎么样?把所有的数组的数组中,这样就可以通过他们全部循环容易,并使用自定义in_array()
函数来检查自己是否已经存在?
how about this? putting all the array's in an array, so you can loop through them all easily, and use a custom in_array()
function to check if they are already existing?
有关这种方式的好处是,它不限制脚本仅仅4阵列,它遍历所有的阵列也将你在一起。
The good thing about this way is that it doesn't limit the script to just four array's, as it will loop through all the array's you get together.
$a = [1,2,3,4,5];
$b = null;
$c = [5,4,3,2,1];
$d = [1,2];
$array_stack = array($a, $b, $c, $d);
$new_array = array();
foreach($array_stack as $stack){
if(!is_array($stack)) continue;
foreach($stack as $value){
if(!in_array($value, $new_array)) $new_array[] = $value;
}
}
print_r($new_array);
这篇关于PHP数组合并唯一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!