二维数组中具有重复元素值的数组元素的总和

时间:2020-09-02 11:14:35

标签: php laravel multidimensional-array

我有一个多数组,其中有一些重复的值,这些值与payment_name相同(payment_name是一个元素) 我想对每个具有相同payment_name的数组的数量求和,并将数量显示为一个。现在,总和是所有金额的数组。任何帮助将不胜感激。

var_export($ num)结果看起来像这样

array( 
    'items' => array ( 
        '2020-08-04' => array ( 
            0 => array ( 
                0 => array ( 
                    'payment_name' =>'Cash',
                    'amount_paid' => array (
                        0 => '0', 
                    ),
                ), 
            ), 
            1 => 0, 
        ),
        '2020-08-05' => array ( 
            0 => array( 
                0 => array ( 
                    'payment_name' => 'Cash', 
                    'amount_paid' => array ( 
                            0 => '0', 
                            1 => '0', 
                            2 => '165', 
                    ), 
                ),
                1 => array ( 
                    'payment_name' => 'Mpesa', 
                    'amount_paid' => array ( 
                            0 => '0', 
                            1 => '0',
                            2 => '165', 
                    ), 
                ), 
            ), 
            1 => 165, 
        ), 

我期望的数组应该是这样,支付的金额应该是总数,而不是所有金额的数组:

    "2020-08-05" => array:2 [▼
      0 => array:2 [▼
        0 => array:2 [▼
          "payment_name" => "Cash"
          "amount_paid" => "0"
        ]
        1 => array:2 [▼
          "payment_name" => "Mpesa"
          "amount_paid" =>  "165"
          ]
        ]
      ]
      1 => 165
    ]

我的代码如下

$requests = $builder->get()->groupBy('date');

$num = $requests->map(function ($row) {

    $result = array();

    $ttl = $row->sum('amount_paid');

    $row = $row->toArray();

    $names = array_column($row, 'payment_name');
    $amount = array_column($row, 'amount_paid');

    $unique_modes = array_unique($names);

    foreach ($unique_modes as $name) {
        $this_keys = array_keys($names, $name);
        $qty = array_sum((array_intersect_key($amount, array_combine($this_keys, $this_keys))));
        $result[] = array("payment_name"=>$name, "amount_paid"=>$amount);
    }
    
    return [$result, $ttl ];
});

return $num;

1 个答案:

答案 0 :(得分:0)

我使用以下代码解决了我的问题:

$num = $requests->map(function ($row) {

            $result = array();

            $ttl = $row->sum('amount_paid');

            $row = $row->toArray();

            $final_array = [];

            foreach($row as $arr){
            $final_array[$arr['payment_name']]['payment_name'] = $arr['payment_name'];
            $final_array[$arr['payment_name']]['amount_paid'] = (isset($final_array[$arr['payment_name']]['amount_paid']))? $final_array[$arr['payment_name']]['amount_paid']+$arr['amount_paid'] : $arr['amount_paid'];    
            }
            $final_array = array_values($final_array);

            return [$final_array, $ttl];

        });