作为有序树的产品选择

Product Selections as Ordered Tree

我的产品具有如下可选变体:

凉鞋

  1. 颜色:红、绿、蓝
  2. 尺码:小号、中号、大号
  3. 品牌:品牌X,品牌Y

每个产品变体都与一组 select 离子相关。 示例: 如果我 select 颜色:红色,尺码:大号,品牌:brandX,这将与 ID 为 820 的产品相关。

选项树应该是这样的:

"optionTree": [
        [
            0,
            0,
            [
                820,
                0
            ]
        ],
        [
            0,
            [
                0,
                821
            ],
            [
                823,
                0
            ]
        ],
        [
            [
                824,
                825
            ],
            0,
            0
        ]
    ]

可以看出,有3个产品选项可供选择,因此树的深度为3。 阵列的每个级别都与产品选项相关。第一个深度涉及颜色,第二个深度涉及尺寸,第三个涉及品牌(有可能是可变数量的选项,而不仅仅是 3)。因此,将整个数组遍历到底部将得到一个与所有 3 个选择匹配的产品 ID。 (选择的索引与'optionTree'数组中的索引有关,也用0表示死胡同)

问题: 我如何在数组树中排序产品 selection 变体,使其与各自的选择相关?

假设我有一系列产品,我想将其插入到一个空树中:

$products_to_add = [
            [
                "choices" => ['red', 'medium', 'brandX'],
                "product_id" => 820
            ],
            [
                "choices" => ['red', 'small', 'brandY'],
                "product_id" => 821
            ],
            [
                "choices" => ['green', 'small', 'brandX'],
                "product_id" => 822
            ],
            [
                "choices" => ['blue', 'large', 'brandY'],
                "product_id" => 823
            ],
        ]

我如何将上面的数组转换为像之前显示的那样连贯的 'optionTree'? (php 或 javascript 都可以)

您可以使用一个循环,在这个循环中您可以随时改变最终的树。在开始之前,您可以准备一个辅助结构,将变体的名称(如“red”)转换为目标结构的相关(子)数组中的索引。在 PHP:

$props = [
    array_flip(["red", "green", "blue"]),
    array_flip(["small", "medium", "large"]),
    array_flip(["brandX", "brandY"])
];

然后在主循环中,您可以受益于 =& 赋值,让指针遍历结果树并在到达时添加 null 引用(我更喜欢这个而不是 0)第一次去某家分店

$optionTree = null;
foreach($products_to_add as $product) {
    $node =& $optionTree;
    foreach ($product["choices"] as $depth => $name) {
        if ($node == null) $node = array_fill(0, count($props[$depth]), null);
        $node =& $node[$props[$depth][$name]];
    }
    $node = $product["product_id"];
}
unset($node); // Safety, since it is a reference

在 运行 此代码之后,$optionTree 将具有所需的值。