0

My question is about how to add the values from two different arrays, that each have 20 records.

$array1

Array
(
    [0] => mysqli_result Object
        (
            [current_field] => 0
            [field_count] => 1
            [lengths] => 
            [num_rows] => 220
            [type] => 0
        )


    [1] => mysqli_result Object
        (
            [current_field] => 0
            [field_count] => 1
            [lengths] => 
            [num_rows] => 70
            [type] => 0
        )

$array2

Array
(
    [0] => mysqli_result Object
        (
            [current_field] => 0
            [field_count] => 1
            [lengths] => 
            [num_rows] => 280
            [type] => 0
        )

[1] => mysqli_result Object
        (
            [current_field] => 0
            [field_count] => 1
            [lengths] => 
            [num_rows] => 30
            [type] => 0
        )

I would like to get a third array like that (adding the values of $array1 and $array2):

Array
(
    [0] => mysqli_result Object
        (
            [current_field] => 0
            [field_count] => 1
            [lengths] => 
            [num_rows] => 500
            [type] => 0
        )

[1] => mysqli_result Object
        (
            [current_field] => 0
            [field_count] => 1
            [lengths] => 
            [num_rows] => 100
            [type] => 0
        )

How do I do this? All operations I've tried only added the values one after another (new array with 40 rows), not adding them.

EDIT SOLUTION

$array3 = array();
for ($i = 0; $i < count($array2); $i++) {
array_push($array3, $array1[$i]->num_rows + $array2[$i]->num_rows); 
}
Lama222
  • 13
  • 2

3 Answers3

0

if you want to add every single value of an array($array1) to another array($array3) you need to take a foreach like this :

foreach($array1 as $array) {
    $array3[] = $array;
}
0

One possible way to do that could be using a for loop and use the index of the arrays to add the num_rows of $array1 to $array2:

for ($i = 0; $i < count($array1); $i++) {
    $array2[$i]->num_rows += $array1[$i]->num_rows;
}
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

Try

$resultArray = array_merge($array1,$array2);
doron
  • 1
  • 1
  • this way the values of the second array add to the first, giving 40 records instead of 20, and the values are not additioned – Lama222 Nov 10 '18 at 19:37