I want to sum an associative array values.The array was created from SQL query.
I tried to sum with array_sum,but array sum was not worked because,my array is not a typical array ($array=array(1,2,3)). Array_sum will return 0.
public function getAge(){
if(isset($_SESSION['age_hold']) && !empty($_SESSION['age_hold']) ){
$sqlAge="SELECT age FROM unisex
WHERE age >=".$_SESSION['age_hold'] ;
$age= Yii::$app->db->createCommand($sqlAge)->queryAll();
return $age;
}
}
$age=$this->getAge();
$length=count($age);
$ageSummation=0;
foreach($age as $key=>$item) {
$ageSummation=$ageSummation+$item;
}
Displaying $age array:
Array ( [0] => Array ( [age] => 90 ) [1] => Array ( [age] => 91 ) [2] => Array ( [age] => 92 ) [3] => Array ( [age] => 93 ) [4] => Array ( [age] => 94 ) [5] => Array ( [age] => 95 ) [6] => Array ( [age] => 96 ) [7] => Array ( [age] => 97 ) [8] => Array ( [age] => 98 ) [9] => Array ( [age] => 99 ) [10] => Array ( [age] => 100 ) )
When i run the code with that foreach, the error is "Unsupported operand types".
I expect to output to be 90+91+92+...+100
The items in $age
are arrays, not integers. You're getting ""Unsupported operand types" because you're trying to add them to 0.
You can use array_column to sum the age key.
$ageSummation = array_sum(array_column($age, 'age'));
You could also do it in your query, unless you're going to use the individual values for something. I see you also have $length=count($age);
in your code, which suggests you may be calculating an average age - you can do that in the query as well if you like.
SELECT AVG(age) FROM unisex WHERE age >= ?;
You're probably looking for array_column() to get all of the age
values in the nested array:
array_sum(array_column($age, 'age'))
Or if you have other logic to apply in the loop, you could just use the age
key in your existing code:
foreach($age as $item)
$ageSummation=$ageSummation+$item['age'];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.