从多个数组获取项目的每种组合-PHP

时间:2018-07-26 11:26:54

标签: php sql arrays sorting

我已经创建了一个电子商务网站,并正在尝试扩展它。

以前,每个产品都可以具有属性,例如颜色,因此,当用户选择产品时,他们可以选择自己喜欢的颜色。

我现在正尝试为每个产品添加多个属性,例如,这可能是颜色和尺寸。

但是,每种产品的定价都不同,所以我试图弄清楚如何在后端定价。

不幸的是,我无法真正显示我的所有代码,因为还有很多其他事情确实不适合这个问题,例如供应商给我们提供了不同货币和汇率的成本价格等。

主要问题是当我选择产品时,适用的属性位于数组中。像这样:

[0]=>Color,[1]=>Size

在这只是一个属性之前,我可以从数据库中查询Color并执行以下操作:

foreach($color_query as $color){
    //generate form for pricing
}

现在,具有多个属性,我想做类似的事情:

foreach(combination of colors and sizes){
    //generate form for pricing
}

所以我要寻找的东西是这样的:

Small Red
Medium Red
Large Red
Small Blue
Medium Blue
Large Blue
Small Green
Medium Green
Large Green

**注意:“大小”和“颜色”仅是示例,我将具有多个属性,并且它们可以具有多个值,因此使用这些示例,我可能最多具有5种尺寸,但可能有15种颜色。

我将如何获得颜色和尺寸的组合的任何想法将不胜感激。

/ -----------编辑---------- \

我知道这是一个很难解释的问题,因此我将通过代码片段来尝试更好地理解。

我在数据库中查询产品,这给了我一串用逗号分隔的值,它们是我的属性集的ID。

$attributes = $_GET['attribute'];
$attribute_array = explode(',',$attributes);
$attribute_array = array_diff($attribute_array, array("")); //this line just gets rid of the empty value after the last comma
foreach($attribute_array as $attribute){
//start generating table    
$params = [$attribute];
    $sql = "SELECT * FROM attributes WHERE id=?";
    $attributeResult = DB::run($sql,$params);
    foreach ($attributeResult as $value) {
        //generate form for pricing to go into table
    }
}
//close table

在这种情况下,我认为其他答案中的建议对我不起作用,因为我在查询之间使用PHP进行了其他操作,例如获取需要生成完整定价表(如供应商货币和交易所)的其他内容等等。

0 个答案:

没有答案