Rumah > Soal Jawab > teks badan
P粉0468781972023-08-21 00:52:52
Fungsi yang mencipta produk Cartesian bagi semua pilihan telah diilhamkan oleh jawapan kepada soalan ini.
<?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);
Jika anda hanya berminat dengan rentetan sku, anda boleh memudahkan fungsi untuk:
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; }
Saya pasti seseorang boleh memberikan jawapan yang lebih cekap, tetapi jawapan ini menghasilkan output yang diingini berdasarkan data contoh anda.