合并具有相同ID的数组

时间:2018-11-26 20:17:37

标签: php

我有以下数组

Array ( [id] => 1 [name] => [cat_name] => Food & Beverage [quantity] => 1
 [price] => 25 [image] => books_image/calories_fat_carbohydrate.png )

 Array ( [id] => 2 [name] => [cat_name] => Food & Beverage [quantity] => 5 
[price] => 38 [image] => books_image/the_law_relating_to_food.png )

 Array ( [id] => 3 [name] => [cat_name] => Food & Beverage [quantity] => 5 
[price] => 19 [image] => books_image/it_starts_with_food.png )

 Array ( [id] => 3 [name] => [cat_name] => Food & Beverage [quantity] => 2
 [price] => 19 [image] => books_image/it_starts_with_food.png )

在$ _SESSION ['cartitem']对象中,键为id

我的问题是我与id=3重复,并且我想要的输出是

Array ( [id] => 1 [name] => [cat_name] => Food & Beverage [quantity] => 1
 [price] => 25 [image] => books_image/calories_fat_carbohydrate.png )

 Array ( [id] => 2 [name] => [cat_name] => Food & Beverage [quantity] => 5 
[price] => 38 [image] => books_image/the_law_relating_to_food.png )

 Array ( [id] => 3 [name] => [cat_name] => Food & Beverage [quantity] => 7 
[price] => 19 [image] => books_image/it_starts_with_food.png )

基本上由相同的id合并并添加quantity字段。有没有一种简单的方法可以在php中做到这一点?

我不想删除重复项。对我而言,重复项很重要,因为它们有一定数量,我需要添加它们。

1 个答案:

答案 0 :(得分:1)

您在这里:

// DEFINE SORTING CRITERIA
function sort_ids($a, $b) {
    return $a['id'] > $b['id'];
}
// DEFINE ARRAY OF ARRAYS
$arrays = array(
    array( 'id' => 1, 'name' => '', 'cat_name' => 'Food & Beverage', 'quantity' => 1,
    'price' => 25, 'image' => 'books_image/calories_fat_carbohydrate.png' ),

    array( 'id' => 2, 'name' => '', 'cat_name' => 'Food & Beverage', 'quantity' => 5, 
   'price' => 38, 'image' => 'books_image/the_law_relating_to_food.png' ),

    array( 'id' => 3, 'name' => '', 'cat_name' => 'Food & Beverage', 'quantity' => 5, 
   'price' => 19, 'image' => 'books_image/it_starts_with_food.png' ),

    array( 'id' => 3, 'name' => '', 'cat_name' => 'Food & Beverage', 'quantity' => 2,
    'price' => 19, 'image' => 'books_image/it_starts_with_food.png' ),

    array( 'id' => 1, 'name' => '', 'cat_name' => 'Food & Beverage', 'quantity' => 1,
    'price' => 25, 'image' => 'books_image/calories_fat_carbohydrate.png' ),

    array( 'id' => 2, 'name' => '', 'cat_name' => 'Food & Beverage', 'quantity' => 5, 
   'price' => 38, 'image' => 'books_image/the_law_relating_to_food.png' )
);
// SORT ARRAY OF ARRAYS FIRST
usort($arrays, 'sort_ids');
// MERGE DUPLICATES
$record_number = count($arrays);
for ($i=0; $i<$record_number; $i++) {
    // if this is not the first loop and if this is a duplicate
    if(isset($temp_id) && $temp_id == $arrays[$i]['id']) {
        // add quantity of the previous array here
        $arrays[$i]['quantity'] += $temp_quantity;
        // unset previous array
        unset($arrays[$i-1]);
    }
    $temp_id = $arrays[$i]['id'];
    $temp_quantity = $arrays[$i]['quantity'];
}
// PRINT ARRAY OF ARRAYS
echo '<pre>';
print_r($arrays);
echo '</pre>';