PHP 生成像 prestashop 这样的组合



我想管理我的数组,但我不知道该怎么做。

当我添加产品时,我可以选择许多属性,例如颜色,尺寸。有时我有超过 2 个属性。

$table = array(
    'color' => array('1', '2'),
    'size' => array('37', '38'),
    'other' => array('a', 'b'),
    ...
);

我正在寻找的是得到这个结果:

$table = array(
    '0' => array('1', '37','a'),
    '1' => array('1', '37','b'),
    '2' => array('1', '38','a'),
    '3' => array('1', '38','b'),
    '4' => array('2', '37','a'),
    '5' => array('2', '37','b'),
    '6' => array('2', '38','a'),
    '7' => array('2', '38','b'),
);    

以下是生成属性列表及其选项的所有组合的一种方法:

function generateCombinations(array $attributes)
{
    $combinations = array(array());
    foreach ($attributes as $options) {
        $new_combinations = array();
        foreach ($combinations as $combination) {
            foreach ($options as $option) {
                $new_combination = $combination;
                $new_combination[] = $option;
                $new_combinations[] = $new_combination;
            }
        }
        $combinations = $new_combinations;
    }
    return $combinations;
}

它的工作原理是迭代地为每个属性构建组合列表:

initialise: [[]]
1st attribute: [[1],[2]]
2nd attribute: [[1,37],[1,38],[2,37],[2,38]]
3rd attribute: [[1,37,a],[1,37,b],[1,38,a],[1,38,b],[2,37,a],[2,37,b],[2,38,a],[2,38,b]]
... and so on if there are additional attributes

您可以使用示例数据调用该函数,如下所示:

$table = array(
    'color' => array('1', '2'),
    'size' => array('37', '38'),
    'other' => array('a', 'b'),
);
$combinations = generateCombinations($table);
var_dump($combinations);

这给出了以下输出(使用 php 5.6 测试(:

array(8) {
  [0]=>
  array(3) {
    [0]=>
    string(1) "1"
    [1]=>
    string(2) "37"
    [2]=>
    string(1) "a"
  }
  [1]=>
  array(3) {
    [0]=>
    string(1) "1"
    [1]=>
    string(2) "37"
    [2]=>
    string(1) "b"
  }
// 6 other rows omitted ...

最新更新