在数组PHP中合并重复项[关闭]
问题描述:
I have an array generated daily that will have duplicate products in it.
[0] => Array
(
[product_id] => 85
[name] => Widescreen Espresso v6.1
[quantity] => 1
)
[1] => Array
(
[product_id] => 85
[name] => Widescreen Espresso v6.1
[quantity] => 2
)
[2] => Array
(
[product_id] => 114
[name] => Panama Esmerelda Diamond Mountain
[quantity] => 1
)
I want to find duplicate products and total them up in an array that would look like this:
[0] => Array
(
[product_id] => 85
[name] => Widescreen Espresso v6.1
[quantity] => 3
)
[1] => Array
(
[product_id] => 114
[name] => Panama Esmerelda Diamond Mountain
[quantity] => 1
)
UPDATE:
I didn't want to remove the duplicates I want to merge duplicates so that the quantity of the product is added together. I managed to work a solution to it with the help of Meenesh Jain's answer below.
$final_array = array();
foreach($order_data as $item => $item_value) {
$pid = $item_value['product_id'];
if(!isset($final_array[$pid])) {
$final_array[$pid] = $item_value;
} else {
$final_array[$pid]['quantity'] += $item_value['quantity'];
}
}
print_r(array_values($final_array));
答
You can do it with mysqli
OR
you can apply a custom method on your array
$temp_array = $new_array = array();
foreach($array as $key => $arr_values){
if(!in_array($arr_values['product_id'], $temp_array)){
array_push($temp_array, $arr_values['product_id']);
array_push($new_array,$array[$key]);
}
}
// this code will do the trick
答
My try:
function newArray($oldarray){
$newarray;
$newarray[0] = $oldarray[0];
$ids;
$ids[0] = array($oldarray[0][product_id],0);
for($i = 1; $i < count($oldarray);$i++){
$add = true;
for($x = 0; $x < count($ids);$x++){
if($oldarray[$i][product_id] == $ids[$x][0]){
$add = false;
$newarray[$ids[$x][1]-1] = array($newarray[$ids[$x][1]-1][product_id],$newarray[$ids[$x][1]-1][name],$newarray[$ids[$x][1]-1][quantity]+$oldarray[$i][quantity]);
}
}
if($add == true){
$newarray[count($newarray)] = $oldarray[$i];
$ids[count($ids)] = array($oldarray[$i][product_id],count($newarray));
}
}
return $newarray;
}
答
You need to use this function (need to pass $array=name of array and $key as 'product_id'):
function super_unique($array,$key)
{
$temp_array = array();
foreach ($array as &$v) {
if (!isset($temp_array[$v[$key]]))
$temp_array[$v[$key]] =& $v;
}
$array = array_values($temp_array);
return $array;
}
Example :
<?php
$vikas=array('0' => array
(
'product_id' => 85,
'name' => "Widescreen Espresso v6.1",
'quantity' => 1
),
'1' => array
(
'product_id' => 85,
'name' => "Widescreen Espresso v6.1",
'quantity' => 2
),
'2' => array
(
'product_id' => 114,
'name' => "Panama Esmerelda Diamond Mountain",
"quantity" => 1
)
);
function super_unique($array,$key)
{
$temp_array = array();
foreach ($array as &$v) {
if (!isset($temp_array[$v[$key]]))
$temp_array[$v[$key]] =& $v;
}
$array = array_values($temp_array);
return $array;
}
//print_r(array_unique($vikas['product_id']));
$vik=super_unique($vikas,'product_id');
print_r($vik);
?>