问题描述:

I have an array. I am trying to print the values of the array like this

`print_r($travellers_data['variation']);`

so it is showing me data like this.

`Array`

(

[adults_travelers] => 1

[child_travelers] => 2

[infant_travelers] => 4

)

Array

(

[adults_travelers] => 12

[child_travelers] => 11

[infant_travelers] => 14

)

Here you can see there are two array blocks containing different age group of travellers.

Now I want to get sum of the total travellers for both the array block. so the result should be like this

`total_travellers = adults_travelers + child_travelers + infant_travelers;`

total_travellers = 13 + 13 + 18 = 44;

so someone tell me how to get the sum of two array blocks. Any help and suggestions will be really appreciable. Thanks

```
$travelers = [
['adults_travelers' => 1, 'child_travelers' => 2, 'infant_travelers' => 4],
['adults_travelers' => 12, 'child_travelers' => 11, 'infant_travelers' => 14]
];
$sum = array_reduce($travelers, function ($sum, array $array) {
return $sum + array_sum($array);
});
```

since `$travellers_data['variation']`

is an array of arrays, we need to loop over it and then sum the individual arrays and add them to our total count. php has a function `array_sum`

which conveniently totals the elements of an array, and it is clever enough to just look at the values of an associative array. we can put it all together into a very simple solution like this:

```
$sum = 0;
foreach($travellers_data['variation'] as $arr)
{
$sum += array_sum($arr);
}
```

this assumes that your arrays ONLY contain traveler information as shown in your question, and not some other values

Thanks for those answers. I just did it my self like this

```
$total_persons = array();
foreach($travellers_datas as $travellers_data) {
$adult_travellers = $travellers_data['variation']['adults_travelers'];
$child_travelers = $travellers_data['variation']['child_travelers'];
$infant_travelers = $travellers_data['variation']['infant_travelers'];
$total_travellers = $adult_travellers + $child_travelers + $infant_travelers;
array_push($total_persons, $total_travellers);
}
$total_travellers_person = array_sum($total_persons);
```