通过ID更新阵列

时间:2018-11-26 23:29:42

标签: php

我有以下数组

    $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' => 1, 'name' => '', 'cat_name' => 'Food & Beverage', 'quantity' => 2,
        'price' => 19, 'image' => 'books_image/it_starts_with_food.png' )
    );

我想要的输出是:

$arrays = array(
    array( 'id' => 1, 'name' => '', 'cat_name' => 'Food & Beverage', 'quantity' => 3,
    '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' ),

);

基本上,当我找到具有相同键(“ ID”)的数组时,我想将它们添加到数量中。 如何在php中轻松做到这一点?我一直在绊脚石,并尝试了以下方法,但根本没有用。

for ($i=0; $i<count($arrays); $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'];
}

1 个答案:

答案 0 :(得分:1)

为此可以使用array_reduce

Failed to perform checkout on agent: Problem while checkout on agent: java.lang.IllegalArgumentException: Repository config file C:\BuildAgent\system\git\git-F58F7104.git\config invalid Cannot read file C:\BuildAgent\system\git\git-F58F7104.git\config

Demo here