我有一个市场,卖家可以单独销售多种产品并指定运输选项,将运输选项与多对多关系中的产品联系起来。
在购物车控制器中,我正在尝试智能地删除运输选项,以便卖家不会因运费而花费太少。
例如,考虑一个包含两种产品的购物车。卖家为每件产品选择了一种送货方式:
$products = array(
array(
'id' => 1,
'name' => 'Lightweight widget',
'shipping_option_ids' => array(
1
)
),
array(
'id' => 2,
'name' => 'Heavyweight widget',
'shipping_option_ids' => array(
2
)
)
);
以下是两种送货方式:
$shipping_options = array(
array(
'id' => 1,
'name' => 'Cheap shipping option',
'price' => 100
),
array(
'id' => 2,
'name' => 'Expensive shipping option',
'price' => 200
)
);
因此,我们有两种产品,每种产品都链接到不同的运输选项。使用昂贵的运输选项,两种产品都可以在同一个包装中运输。
现在,我需要从送货选项数组中删除便宜的送货选项。这将使客户只选择一种选择 - 昂贵的选择。
购物车中的两个或多个产品没有至少一个共同的运输选项。
删除所有运费选项,但使用最昂贵的运送选项链接到产品的选项除外。
答案 0 :(得分:0)
我通过以下方式解决了问题:
// Prepare for removal procedure
foreach ($store['shipping_options'] as &$shipping_option)
{
$shipping_option['removal_candidate'] = FALSE;
}
unset($shipping_option);
// Label shipping options that aren't linked to all products:
foreach ($products as $product)
{
if (!in_array($shipping_option['id'], $product['shipping_option_ids']))
{
$shipping_option['removal_candidate'] = TRUE;
}
}
$number_of_shipping_options = count($shipping_options);
// Loop through each shipping option:
for ($i = 0; $i < $number_of_shipping_options; $i++)
{
$shipping_option_a = $shipping_options[$i];
// Compare each shipping option with each of the other shipping options:
foreach ($shipping_options as $key => $shipping_option_b)
{
// Compare different shipping options only:
if ($shipping_option_a['id'] != $shipping_option_b['id'])
{
// Remove the shipping option with the lowest price:
if ($shipping_option_a['price'] < $shipping_option_b['price'])
{
if ($shipping_option_a['removal_candidate'])
{
unset($store['shipping_options'][$i]);
$shipping_options_removed = TRUE;
$number_of_shipping_options = count($store['shipping_options']);
}
elseif ($shipping_option_a['price'] > $shipping_option_b['price'])
{
if ($shipping_option_b['removal_candidate'])
{
unset($store['shipping_options'][$key]);
$shipping_options_removed = TRUE;
$number_of_shipping_options = count($store['shipping_options']);
}
}
}
}
}
// Refresh key numbers:
$store['shipping_options'] = array_values($store['shipping_options']);
}