【问题标题】:Best practice for looping through a nested array php循环嵌套数组php的最佳实践
【发布时间】:2018-04-22 12:58:04
【问题描述】:

我正在用 PHP 编写代码。

我想做的是像 Magento2 中的可配置产品或 Woocommerce 中的可变产品。我要求用户输入产品的属性,例如颜色、尺寸等。

将每个属性视为一个属性类别,其中包含属性,例如“颜色”将具有“红色”、“绿色”、“蓝色”等属性。大小将具有“大”、“小”、“中”等属性。

现在,我需要创建一个循环,它采用所有尺寸、颜色和其他选择的属性并返回所有可能的配置。同时,由于用户可以添加或删除属性,因此没有预定义要循环的属性数量。

例如,如果我有这个:

Color - - - - - - - - Size - - - - - - - - Shape
Red - - - - - - - - - Large - - - - - - -  Square
Green - - - - - - - - Medium - - - - - - - Rounded
Blue - - - - - - - -  Small - - - - - - - - 

所以我必须拥有各种大小和形状的每种颜色:

Red - Large - Square
Red - Large - Rounded
Red - Medium - Square
Red - Medium - Rounded
Red - Small - Square
Red - Small - Rounded

其他属性也一样。

实现它的最佳做法是什么?

【问题讨论】:

  • 列出所有可能的10+属性组合是多余的,用户会发疯的。你知道吗?对于每个属性,在页面上放置一个<select> 列表,用户将选择他想要的...问题解决了
  • @ThanhTrung 用户有一个复选框,用于选择他想要使用的属性。我需要能够输出每个配置,因为在商店中,不同颜色的产品具有不同的 SKU,因此我必须拥有该选项
  • 你想要什么作为返回值?一个字符串分隔的数组还是一个复杂的数组结构?
  • @ThanhTrung 我希望它是该模式中的字符串:`attr-1 - attr-2 - attr-n

标签: php loops


【解决方案1】:

您需要为此进行递归。

function getCombinations($attributes){
    $combinations = [];
    buildCombinationChain($attributes,0,[],$combinations);

    // encode combinations to desired string format
    $result = [];
    foreach ($combinations as $combination) {
        $result[] = implode(' - ', $combination);
    }

    return $result;
}

function buildCombinationChain($attributes,$index,$chain,&$output){
    if($index>=count($attributes)){
        // we have reached the last attribute, stop recursion and push the current chain to the output array
        $output[] = $chain;
        return;
    }
    foreach ($attributes[$index] as $attribute) {
        $new_chain = $chain; // create a copy of the current chain
        $new_chain[] = $attribute; // and add the current attribute to it
        buildCombinationChain($attributes,$index+1,$new_chain,$output); // continue recursively on the next attribute group
    }
}



$attributes = [
    ['Red', 'Green', 'Blue'],
    ['Large', 'Medium', 'Small'],
    ['Square', 'Rounded']
];

echo json_encode(getCombinations($attributes));

【讨论】:

  • 首先感谢(非常感谢!:D)。其次,如何将每个组合上传到数据库,而列中的每个字段将包含上述 1 个组合?
  • @Omer 创建两个表,一个用于产品本身,另一个包含指向产品行 ID 的每个产品属性(键值)的行。
猜你喜欢
  • 2019-03-16
  • 2017-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-07
  • 1970-01-01
  • 2013-10-02
相关资源
最近更新 更多