我遇到了一个小问题。我正在开发一个小包装/产品清单。 如果您正在观看套餐,我的网站应该会向您显示哪些产品在那里。 如果产品中有多次,则应删除该数组,并且剩余数组的值应为+ 1(每个已删除的数组)。
所以这是我的代码:
// $products_in_package has all products in it
// First of all, the products come from a db and don't have a count
// So i first give them a count of 1
foreach ($products_in_package as $product => $value) {
$products_in_package[$product]['count'] = intval(1);
}
foreach ($products_in_package as $product) {
$id_to_find = intval($product['ID']);
$product_count = intval($product['count']);
$found_id = 0;
// Now I try to find any ident products
// If found and over 1 time (beacouse he finds the first too of course)
// Then delete this array and count up the products count
for ($i=0; $i <= count($products_in_package); $i++) {
if(intval($products_in_package[$i]['ID']) === $id_to_find){
$found_id++;
if($found_id > 1){
$product_count = $product_count + 1;
$product['count'] = $product_count;
unset($products_in_package[$i]);
array_merge($products_in_package);
while($i > $products_in_package){
$i = 0;
}
}
}
}
}
我得到的是正确的多维数组,但计数仍为1。 代码有什么问题?
每次我尝试记录代码时,我都会得到正确的整数。 (不,我已经尝试删除了chache) 但是如果我将数组从循环中记录下来,我总是得到1的计数。
答案 0 :(得分:3)
$product
是数组元素的副本,因此当您执行$product['count'] = $product_count
时,您将分配给副本,而不是原始数组。
您可以使用foreach
:
foreach ($products_in_package as &$product) {