Heim > Fragen und Antworten > Hauptteil
P粉0468781972023-08-21 00:52:52
创建所有选项的笛卡尔积的函数受到这个问题的答案的启发。
<?php function all_skus(array $product) { $skus = []; $result = [[]]; foreach ($product['options'] as $key => $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);
如果你只对sku字符串感兴趣,你可以简化函数为:
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; }
我相信有人可以提供一个更高效的答案,但这个答案根据你的示例数据产生了所需的输出。