douluan5444 2019-05-09 07:28
浏览 180

在数组中添加所有相同类型的对象

I have an array of objects which I am trying to condense in php. This is my array

$proposedStudentFeeCollection = [{"id":1,"student_id":"1","feeType_id":"2","proposed_fee":"5000"},
{"id":2,"student_id":"1","feeType_id":"1","proposed_fee":"5000"},
{"id":3,"student_id":"1","feeType_id":"1","proposed_fee":"2000"},
{"id":4,"student_id":"1","feeType_id":"2","proposed_fee":"15000"},
{"id":5,"student_id":"1","feeType_id":"2","proposed_fee":"5000"},
{"id":6,"student_id":"1","feeType_id":"11","proposed_fee":"9000"},
{"id":7,"student_id":"1","feeType_id":"1","proposed_fee":"20000"},
{"id":8,"student_id":"1","feeType_id":"16","proposed_fee":"1000"}]

I want to get a "new" simplified array which gives me sum of same feeType_id like so

[{"id":1,"student_id":"1","feetype_id":"1","proposed_fee":"27000"},
{"id":2,"student_id":"1","feetype_id":"2","proposed_fee":"25000"},
{"id":3,"student_id":"1","feetype_id":"11","proposed_fee":"9000"},
{"id":4,"student_id":"1","feetype_id":"16","proposed_fee":"1000"}]

I am trying to do it like so

$myArray = array();
for($i=0; $i<2; $i++){
    $tempObject = $proposedStudentFeeCollection[$i];
    for($j=count($proposedStudentFeeCollection)-1; $j >= 0; $j--) {
        if($tempObject->feetype_id == $proposedStudentFeeCollection[$j]->feetype_id){
            $tempObject->proposed_fee += $proposedStudentFeeCollection[$j]->proposed_fee;
            unset($proposedStudentFeeCollection[$j]);
        }
    }
    $myArray[] = $tempObject;
}
return $myArray;

But I am not getting the answer. What is the correct way?

  • 写回答

2条回答 默认 最新

  • doudu6100 2019-05-09 07:52
    关注

    Create an associative array that uses the column that you want to group by as a key. Loop over the original array, and add the row if it doesn't already exist in the result, otherwise just add to the total proposed_fee.

    $totals = [];
    foreach ($proposedStudentFeeCollection as $e) {
        $id = $e['feeType_id'];
        if (isset($totals[$id])) {
            $totals[$id]['proposed_fee'] += $e['proposed_fee'];
        } else {
            $totals[$id] = $e;
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制