0

Here is the sample array and I really can't solved it on my own.

I want to add the values of two different array but I really don't know how

enter image description here

Is that possible to add those two values of array??

Here is my sample code that I have used array_sum() but I end up getting only the values(not the sum of the values)

foreach ($_GET['Reservation'] as $key => $value) {
    foreach ($value as $key2 => $value2) {

        foreach ($value2 as $key3 => $value3) {


            echo array_sum($value2);

        }

    }

}

1 Answer 1

2

Within your foreach loop you can simply use + operator, as you don't need array_sum over here. array_sum is used for summation of array and not strings. So your simplified code is as follows

$arr = ['Reservation' => [3=>[56 => [2],57 => [2]],5=>[43 => [1]]]];
$res = '';
$i = 0;
foreach ($arr['Reservation'] as $key => $value) {
    foreach($value as $v)
        $res[$key] += $v[0];
}
print_r($res);

Output:

Array
(
    [3] => 4
    [5] => 1
)
Sign up to request clarification or add additional context in comments.

5 Comments

thank you sir but it didnt work well in my case,.here is the 2nd example of my array 'Reservation' => array ( 3 => array ( 56 => array ( 0 => '2', ), 57 => array ( 0 => '2', ), ), 5 => array ( 43 => array ( 0 => '1', ), ), ) and the result is 4 then 5,..the expected answer should be 4 then 1
here is the explanation of my array sir: 'Reservation' => array ( 3 => array ( 56 => array ( 0 => '2', ), 57 => array ( 0 => '2', ), ), 5 => array ( 43 => array ( 0 => '1', ), ), ) The number 3 is my RoomTypeID and the 56 and 57 is the RoomNo. of the RoomTypeID(the number 3) and the 2 and 2 values are the number of guest. so foreach RoomTypeID it can have many RoomNo. and in every RoomNo. has number of guest and what i want is the total of the number of guest foreach RoomTypeID
Updated answer have a look
thanks a lot sir it works now :D although i have some errors like this Notice: Undefined Offset i think i can just ignore those, thanks again sir i can now proceed to another page of my thesis :D
but i can now insert those values in my database and works correctly so i think i could just ignore those notices since it wont be seen by the user,.should I still need to solve those notices sir?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.