PHP 个数组 - 3 个数组中的唯一组合

PHP arrays - unique combinations out of 3 arrays

我什至不确定如何解决这个问题,所以我只是在陈述问题。非常感谢任何帮助。

这里有一个包含所有可能值的数组($colors):

$colors = array ('red','blue','green','yellow');

然后是所有可能值的数组 ($boxes) - 由与 $colors:

相同数量的值组成
$boxes = array ('circular','squared','hexagonal','triangular');

第三个数组定义了制作唯一组合的约束条件:

$possible_combos = array  
(  
array('circular','red','blue'),  
array('squared','red','green'),
array('hexagonal','blue','yellow'),
array('triangular','red','green')
);

问题:我如何获得一个新数组 $result 与 key=>value 组合,只是每个框都被分配了一个唯一的颜色在可能的颜色集中

所以一个有效的 $result 数组应该是:

Array ( [circular] => red 
        [squared]  => blue 
        [hexagonal]=> yellow
        [triangular] => green
      ) 

注意:如果您按顺序遍历,'red'、'blue'、'green' 可能会分配给前三个 'boxes',并且可能没有任何东西可供选择第四个框(因为 'yellow' 不允许分配给它。
我在想,首先处理最少出现的 'colors' 但真的不确定如何在语法上处理它。

再次感谢您提前查看!即使是一些关于如何解决问题的帮助也会很好。

以下代码也没有产生正确的输出:

foreach ($colors as $c => $color) {
    foreach ($boxes as $b => $box) {
        for ($i=0; $i < count($colors) ; $i++) {
            if(in_array($possible_combos[$i][1],$colors) && !in_array($possible_combos[$i][1], $result))
            {
                $result[$box] = $possible_combos[$i][1];
                unset($colors[$c]);
                break;
            }
            else if(in_array($possible_combos[$i][2],$colors) && !in_array($possible_combos[$i][2], $result))
            {
                $result[$box] = $possible_combos[$i][2];
                unset($colors[$c]);
                break;
            }
        }
    }
}

I'm thinking, to process the least occurring 'colors' first but really unsure how to handle it syntactically.

考虑到您只有一种盒子类型可以共享多种颜色中的一种这一事实,这是一个很好的直觉。因为你的约束资源是颜色,我认为先按它们对规则进行排序然后你可以按稀缺性分配是有意义的。

https://3v4l.org/u5pBK

$colors = array ('red','blue','green','yellow');

$boxes = array ('circular','squared','hexagonal','triangular');

$possible_combos = array
(
    array('circular','red','blue'),
    array('squared','red','green'),
    array('hexagonal','blue','yellow'),
    array('triangular','red','green')
);

// collect constraints ordered by rarest
foreach ($possible_combos as $constraint) {
    $box = array_shift($constraint);
    foreach ($constraint as $color) {
        $constraints[$color] []= $box;
    }
}

// assign rarest first to last
asort($constraints);
foreach ($constraints as $color => $allowedBoxes) {
    foreach ($allowedBoxes as $box) {
        $key = array_search($box, $boxes);
        // if we have a match, then remove it from the collection
        if ($key !== false) {
            $result[$box] = $color;
            unset($boxes[$key]);
            continue 2;
        }
    }
}

print_r($result);
Array
(
    [hexagonal] => yellow
    [circular] => blue
    [squared] => green
    [triangular] => red
)