查找二维数组

时间:2017-11-16 09:30:22

标签: php

我需要一些组合的帮助,特别是在商店中,它们是每种产品的变体,例如尺寸和颜色。

假设我们有3个可自定义的产品属性: 颜色,尺寸和类型。

对于此特定产品,每个属性都有以下内容: 颜色:[红色,绿色],尺寸:[10,11,15],类型:[人物]

现在根据上面的数据,我需要生成 6 组合,但是如果我们添加另一种类型,它会增加更多。

我已经在我的电路板上画了2个小时,现在试图想出一个理智的算法,这个速度很快,可以在几秒钟内处理成千上万的组合。

举个例子:

$options = ['Color' => ['Red', 'Green'], 'Size' => ['10', '11', '15'], 'Type' => ['person']];
$combinations = generateCombinations($options);

genereateCombinations然后需要生成以下输出:

[
    ['Color' => 'Red', 'Size' => '10', 'Type' => 'person'],
    ['Color' => 'Red', 'Size' => '11', 'Type' => 'person'],
    ['Color' => 'Red', 'Size' => '15', 'Type' => 'person'],
    ['Color' => 'Green', 'Size' => '10', 'Type' => 'person'],
    ['Color' => 'Green', 'Size' => '11', 'Type' => 'person'],
    ['Color' => 'Green', 'Size' => '15', 'Type' => 'person']
];

什么算法可以有效地执行此操作并使用无限输入“标题”? (当然我会更早地执行限制,但算法应该能够无限制地授予世界上所有资源)

扩展我的意思: 此函数还需要能够获取具有100个属性行的数组,而不仅仅是3,无论输入行数多少,它都需要能够动态执行此操作。

1 个答案:

答案 0 :(得分:2)

无论foreach中有多少条目,三个$options循环就足以生成所有组合:

function generateCombinations(array $options)
{
    // Start with one combination of length zero
    $all = array(array());

    // On each iteration append all possible values of the new key
    // to all items in $all; generate this way all the combinations
    // one item longer than before
    foreach ($options as $key => $values) {
        // Move all combinations of length N from $all to $current
        $current = $all;
        // Start with an empty list of combinations of length N+1
        $all = array();
        // Combine each combination of length N 
        // with all possible values for the (N+1)th key
        foreach ($current as $one) {
           foreach ($values as $val) {
              // Put each new combination in $all (length N+1)
              $all[] = array_merge($one, array($key => $val));
           }
        }
    }

    return $all;
}


$options = [
    'Color' => ['Red', 'Green'],
    'Size' => ['10', '11', '15'],
    'Type' => ['person'],
    'Answer' => ['Yes', 'No'],
];

$combinations = generateCombinations($options);
echo(count($combinations));
# 12

它可能会略有改进,但总而言之,如果您事先不知道$options的长度,它会进行大量的重复迭代。如果事先知道$options中的项目数(假设它是N),则N嵌套循环是快速完成的方法。