Reworded title: List all possible product options
P粉976737101
P粉976737101 2023-08-20 10:31:11
0
1
414

以前,我可以轻松处理这样的事情,但自从7年前离开开发世界以来,我失去了开发思维...

我的情况是,我正在尝试输出客户可以选择的每个可能的产品选项以及生成的SKU - 由每个选项的SKU附加到产品的SKU。

数据存储得不好,因为这是一个相当古老的网站。

下面是MySQL中存储数据的示例,以及我在PHP中尝试实现的目标。我将其限制为一个具有多个选项的产品。

products.id products.sku
1 a
options.id options.product_id
1 1
2 1
3 1
4 1
option_values.id option_values.option_id option_values.value
1 1 b
2 1 c
3 1 d
4 2 e
5 2 f
6 3 g
7 3 h
8 4 i
9 4 j
10 4 k

迭代每个选项的每个可能组合,并输出生成的SKU;

可能的SKUs
abegi
acegi
adegi
abfgi
acfgi
adfgi
abehi
acehi
adehi
abegj
acegj
adegj
abegk
acegk
adegk
[等等]

当我像这样写出来时,它似乎非常简单,这让我想知道我是否遗漏了什么...

我目前正在迭代每个产品,对于每个产品的每个选项,然后对于每个选项的每个值,但显然这不能满足每种可能的情况。

DB Fiddle - https://www.db-fiddle.com/f/vHWiKsKi9WUvvDwAa6pqw6/0

谢谢!

P粉976737101
P粉976737101

reply all (1)
P粉046878197

The function that creates the Cartesian product of all options is inspired bythe answer to this question.

 $option) { $append = []; foreach ($result as $options) { foreach ($option as $value) { $append[] = $options + [$key => $value]; } } $result = $append; } foreach ($result as $option_set) { $skus[] = $product['sku'] . implode($option_set); } return $skus; } $pdo = new PDO(/* your stuff here */); $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); $res = $pdo->query(' SELECT `o`.`product_id`, `p`.`sku`, `ov`.`option_id`, `ov`.`value` FROM `products` `p` JOIN `options` `o` ON `p`.`id` = `o`.`product_id` JOIN `option_values` `ov` ON `o`.`id` = `ov`.`option_id`' ); $nested = []; foreach ($res as $row) { $nested[$row->product_id]['options'][$row->option_id][] = $row->value; $nested[$row->product_id]['sku'] = $row->sku; } $skus = []; foreach ($nested as $i => $product) { $skus = array_merge($skus, all_skus($product)); unset($nested[$i]); } var_dump($skus);

If you are only interested in the sku string, you can simplify the function to:

function all_skus(array $product) { $result = [$product['sku']]; foreach ($product['options'] as $option) { $append = []; foreach ($result as $options) { foreach ($option as $value) { $append[] = $options . $value; } } $result = $append; } return $result; }

I'm sure someone can provide a more efficient answer, but this answer produces the desired output based on your example data.

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!