Home » Php » php – sum unique data from multiple array

php – sum unique data from multiple array

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have two arrays from a different database, now I have to print it’s in a table as a combined report. those arrays are

array:3 [▼
  0 => array:6 [▼
    "count_id" => 5
    "count_name" => "NE 28/1"
    "order_qty" => 75100
    "balance_qty" => 75100
    "stock_qty" => "0"
    "order_req" => 75100
  ]
  1 => array:6 [▼
    "count_id" => 13
    "count_name" => "NE 20/1 KH"
    "order_qty" => 2200
    "balance_qty" => 2200
    "stock_qty" => "48400"
    "order_req" => 0.0
  ]
]

and the second array

array:2 [▼
  0 => array:6 [▼
    "count_id" => 13
    "count_name" => "NE 20/1 KH"
    "order_qty" => 2200
    "balance_qty" => 2200
    "stock_qty" => "45420.85"
    "order_req" => 0.0
 ]
 1 => array:6 [▼
   "count_id" => 24
   "count_name" => "NE 24/1 KH"
   "order_qty" => 5150
   "balance_qty" => 5150
   "stock_qty" => "45420.85"
   "order_req" => 0.0
 ]
]

Now I need the common “count_name” Like “NE 20/1 KH” value will sum and print only once. Something Like…

array:3 [▼
  0 => array:6 [▼
    "count_id" => 5
    "count_name" => "NE 28/1"
    "order_qty" => 75100
    "balance_qty" => 75100
    "stock_qty" => "0"
    "order_req" => 75100
  ]
  1 => array:6 [▼
    "count_id" => 13
    "count_name" => "NE 20/1 KH"
    "order_qty" => 4400
    "balance_qty" => 4400
    "stock_qty" => "96800"
    "order_req" => 0.0
  ]
  2 => array:6 [▼
    "count_id" => 24
    "count_name" => "NE 24/1 KH"
    "order_qty" => 5150
    "balance_qty" => 5150
    "stock_qty" => "45420.85"
    "order_req" => 0.0
  ]
]

I try to do it by two foreach loop, but it’s didn’t work. it’s print every data multiple time. so is there anyone to help me, please.

How to&Answers:

It can be done but probably just easier to combine them via the database query in the first place.

// Your arrays of data
$data = [$array1, $array2];

// The fields you want to sum
$sumFields = ['order_qty', 'balance_qty', 'stock_qty', 'order_req'];

// The final array
$combined = [];

foreach ($data as $arr) {
    foreach ($arr as $item) {
        $key = $item['count_id'];
        if (!isset($combined[$key])) {
            $combined[$key] = $item;
        } else {
            foreach ($sumFields as $field) {
                $combined[$key][$field] += $item[$field];
            }
        }
    }
}

// Print result
print_r($combined);

Answer:

You have to loop through them. This code should work

foreach($array1 as $elem1){
    $found = false;
    foreach($array2 as $elem2){
        if($elem1->count_id = $elem2->count_id){
            $found=true
            //Add elements from elem1 to elem2
            break;
        }
    }
    if(!$found){
        array_push($array2, $elem1)        
    }
}

I hope it helps.