0

Hi i know its very simple but im stuck in this. Im fetching data by using join from database.. Now i got the values in array. i want to add these two value in a variable. Code is below..

$sql = "SELECT event_details.max_team_size FROM booking_details INNER JOIN event_details on booking_details.subcategory_id=event_details.id WHERE booking_details.`booking_id` = ".$booking_id." ";

        $command = Yii::$app->db->createCommand($sql);
        $array = $command->queryAll();

$array has got the values like this..

Array
(
[0] => Array
    (
        [max_team_size] => 6
    )

[1] => Array
    (
        [max_team_size] => 8
    )
 )

I want to add these two max_team_size into a single variable and use that later to compare.

5
  • By add you mean by sum of these two variables or concat Commented Oct 13, 2017 at 6:58
  • do you want it in single array? Commented Oct 13, 2017 at 6:58
  • @urfusion sum of these two max_team_size values.. like 6+8= 14 in a $total. Commented Oct 13, 2017 at 7:01
  • @ChetanAmeta No not in array Commented Oct 13, 2017 at 7:01
  • @SalmanRiyaz ok, check my answer Commented Oct 13, 2017 at 7:04

3 Answers 3

2
$sum = 0;
foreach($array as $data){
    $sum  += $data->max_team_size;
}
echo $sum;
Sign up to request clarification or add additional context in comments.

Comments

1

Sum you can get from SQL also by using SUM function

SELECT SUM(event_details.max_team_size) FROM booking_details...

In Yii the solution will be

$sql = "SELECT SUM(event_details.max_team_size) as total FROM booking_details INNER JOIN event_details on booking_details.subcategory_id=event_details.id WHERE booking_details.`booking_id` = ".$booking_id." ";
$command = Yii::$app->db->createCommand($sql);
$array = $command->queryRow();

In PHP to sum particular key in single array you can convert it to single array by using array_column function and then use sum function

$array = array_column($array, 'max_team_size');
$total = array_sum($array);

Note: array_column will work PHP >= 5.5, for PHP < 5.5 you can use foreach loop

Comments

0

Define an empty array like this:

$maxArr = array();

You can run a foreach loop for your array now and add variable. Like this:

foreach($gotArr as $key=>$val){

}

Comments

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.