Answer the question
In order to leave comments, you need to log in
Can't add values of one array by keys?
Good day to all.
I am making an application on Yii2, in the model there is a function that selects two fields from the database for a certain time and returns an array.
Everything works on OpenServer, but when loading on the VPS, the Undefined offset 1 error pops up, as I understand it, due to the addition operation +=
$min = $this->find()->select(['plus','DATE_FORMAT(FROM_UNIXTIME(`date_op`), \'%d.%m.%Y\') as date_op'])->where(['user_id' => yii::$app->user->getId()])->andWhere(['between','date_op', $min, $max + 3600 *24])->orderBy('date_op')->asArray()->all();
foreach($min as $k) {
//Функция сложения дат и доходов
$new[(int) $k['date_op']] += $k['plus'];
}
Answer the question
In order to leave comments, you need to log in
It's easier to fix sql: Add SUM to plus and grouping by date, and it will be unnecessary to add anything in php.
$ind = (int) $k['date_op'];
if (!$new[$ind]) $new[$ind] = 0;
$new[$ind] += $k['plus'];
Thanks everyone.
The solution is:
public function getMaxMonth($min,$max)
{
//$min = $this->find()->select(['plus','date_op'])->where(['user_id' => yii::$app->user->getId()])->andWhere(['between','date_op', $min, $max + 3600 *24])->asArray()->all();
$min = $this->find()->select(['SUM(plus) as plus','DATE_FORMAT(FROM_UNIXTIME(`date_op`), \'%d.%m.%Y\') as date_op'])->where(['user_id' => yii::$app->user->getId()])->andWhere(['between','date_op', $min, $max + 3600 *24])->orderBy('date_op')->groupBy('date_op')->asArray()->all();
$new = [];
foreach($min as $k) {
//Функция сложения дат и доходов
$new[(int) $k['date_op']] = $k['plus'];
//$new[(int) date('d',$k['date_op'])] += $k['plus'];
}
// $diff = Enum::dateList(1,31);
$newdiff = [];
// foreach($diff as $key => $value) {
// $newdiff[$key] += 0;
// }
for($i = 1; $i<32; $i++) {
$newdiff[$i] = 0;
}
$new = ArrayHelper::merge($new,$newdiff);
return $new;
}
public function getMaxYear()
{
$now = date('m',time());
$startyear = strtotime(date("Y-1-1"));
$year = [];
for($i = 1; $i < $now + 1; $i++) {
$diff = $this->getMaxMonth(strtotime(date("Y-$i-1")),strtotime(date("Y-$i-31")));
foreach($diff as $k)
{
$year[$i] += $k;
}
}
return $year;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question