我有一个市场,卖家可以销售多个产品并分别指定运输选项,将运输选项与产品联系在一个多到多的关系中。
在购物车控制器中,我试图明智地删除运输选项,这样卖家就不会因为运输成本而剩下太少的钱。
举个例子,考虑一个购物车,里面有两个产品。卖方选择了每种产品一种运输方案:
$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
)
);因此,我们有两个产品,每个连接到不同的航运选择。使用昂贵的运输选项,这两种产品可以在同一个包裹中运送。
现在,我需要从送货选项数组中删除廉价的送货选项。这将使客户只有一个选择的航运选择-昂贵的一个。
泛化
条件
发布于 2015-04-15 15:47:40
我用以下方式解决了这个问题:
// 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']);
}https://stackoverflow.com/questions/29648133
复制相似问题