【发布时间】:2012-10-07 13:05:34
【问题描述】:
我正在为我的目录设计一个包引擎。在这里,您可以将一定数量的产品添加到包装中并享受折扣。当您订购产品时,脚本必须检测哪些套餐交易适用于您的订单。
这是我的代码:
// packages
$packages["package1"] = array(1,1,2);
$packages["package2"] = array(1,2);
//orderlist
$orderlist = array(1,1,2,1,2,2);
// put the order list in a temp array
$temp_product_array = $orderlist;
foreach($packages as $pname => $package_array)
{
$no_more_package = 0;
do
{
// put the package products in a temp array
$temp_package_array = $package_array;
$is_packages_array = array_intersect($temp_package_array,$temp_product_array);
// if all package values are present
if(count($is_packages_array) == count($temp_package_array))
{
// add package name
$packages_in_order[] = $pname;
// filter the package out of the product list but keep duplicate values
foreach($temp_product_array as $key1 => $pid1)
{
foreach($temp_package_array as $key2 => $pid2)
{
if($pid1==$pid2)
{
unset($temp_product_array[$key1]);
unset($temp_package_array[$key2]);
break; // after removing go to the next product to prevent double erasing
}
}
}
}
else
{
$no_more_package = 1;
}
}
while($no_more_package<1);
}
print_r($packages_in_order);
print_r($temp_product_array);
结果是:
Array ( [0] => package1 [1] => package1 ) Array ( [5] => 2 )
但我希望结果是:
Array ( [0] => package1 [1] => package2 ) Array ( [5] => 2 )
我尝试了array_diff、array_intersect,但它们都不能很好地处理重复值。
有没有人有更好/更有效的方法来解决这个问题?
(PS 由于来源不同,我无法使用关联数组)
【问题讨论】:
-
所以 orderlist 必须包含与包裹相同的产品(并且顺序相同)才能匹配?
-
订单列表以任何可能的顺序包含任意数量的商品 ID。 (在脚本中,包裹是按折扣订购的。)
标签: php arrays array-intersect