检查每个值是否在不同的数组中

时间:2015-07-10 10:53:20

标签: php arrays

我需要检查元素'a'是否存在两次,'b'存在两次,'c'在一组数组中存在一次。每个元素应该有五个不同的数组。

就像是,array1中的'a',array2中的另一个'a',array3中的'b',array4中的另一个'b'和array5中的'c'。应该有至少五个或更多的数组,每个元素应该使用PHP在不同的数组。现在我的代码是

$arr = array(
    $branch1 = array('a', 'b'),
    $branch2 = array('b','c'),
    $branch3 = array('a',  'c'),
    $branch4 = array('c', 'a'),
    $branch5 = array('b', 'a'),
    $branch6 = array('b', 'c', 'a')
    );//This may have any number of branches and any kind of combinations of a, b and c(but each element only once in each array). 

$reqd_branch_count = 5;//required branch count

由于我是php的新手,现在我编写了一个很长的代码,但在尝试新的组合时失败了。如果有人知道,请帮助我。

2 个答案:

答案 0 :(得分:0)

如果我理解正确

合并所有数组,计算所有数组中所有项目的数量并测试你想要的

$arr = array_merge($branch1,$branch2,$branch3,$branch4,$branch5,$branch6);
$count = array_count_values($arr);

echo $count[7]; // 4
echo $count[4]; // 2

所以,yuo可以创造条件

if (($count[7] == 1)  or ($count[7] == 2) or ($count[5] == 2) or ($count[4] == 2))  
   {  any stuff for true}

<强>更新

$arr = array(
$branch1=array('3'),
$branch2=array('4'),
$branch3=array('3','5','7'),
$branch4=array('3','4','7'),
$branch5=array('7'),
$branch6=array('4','7'));
// find rank per branch
$ranks = array_map('max', $arr);
// make array rank => amount
$count = array_replace(array_fill(0,7,0), array_count_values($ranks));

if (($count[7] >= 1) and (($count[7] + $count[5]) >= 2) and (($count[7] + $count[5] + $count[4]) >= 5)) { 
     echo "Satisfy ";
}

答案 1 :(得分:0)

因为这是另一个问题,这是另一个答案

$arr = array(
    $branch1 = array('a'),
    $branch2 = array('b','c'),
    $branch3 = array('a',  'c'),
    $branch4 = array('c', 'a'),
    $branch5 = array('a'),
    $branch6 = array( 'c', 'a')
    );

$names = array('a', 'b', 'c');    // for convenience only 
var_dump(goNext($arr, $names));   // watch result

function goNext($arr, $names) {
    // for each name make array with list of brances where it is
    $in = array(array(), array(), array());
    foreach($arr as $k1 => $branch) 
        foreach($names as $k2 => $letter)
            if(in_array($letter, $branch)) $in[$k2][] = $k1;

    foreach ($in[0] as $i1)  // 1st a
        foreach (array_diff($in[0], array($i1)) as $i2)   // 2nd a
            foreach (array_diff($in[1], array($i1,$i2)) as $i3)  // 1st b
                foreach (array_diff($in[1], array($i1,$i2,$i3)) as $i4)  // 2nd b
                    foreach(array_diff($in[2], array($i1,$i2,$i3,$i4)) as $i5) {
                        // if here we find combination we need
                        // next line only for debug
                        // it shows set of branches that give true
                        //    a           a           b           b           c
                        echo $i1 . " " . $i2 . " " . $i3 . " " . $i4 . " " . $i5;
                        return(true);
                    }
    return(false);   // combination has not found
}