假设我有这样的值(value)
Array
(
[0] => stdClass Object
(
[amount] => 4000.00
[monthyear] => 2018-02
)
[1] => stdClass Object
(
[amount] => 5000.00
[monthyear] => 2018-01
)
)
我想产生一些像这样的值(value)
[5000,4000,0,0,0,0,0,0,0,0,0,0]
我使用了 foreach 循环和 for 循环,但我不明白如何做到这一点,它实际上是按月生成余额报告总和。
是否可以通过 CodeIgniter 生成该值?
我对上述输出的查询是:
$this->cm->select_sum = "amount";
$this->cm->select = "DATE_FORMAT(date,'%Y-%m') as monthyear";
$this->cm->table_name = "personal_balance";
$this->cm->where = array("DATE_FORMAT(date,'%Y')" => date('Y'));
$this->cm->group_by = "DATE_FORMAT(date,'%m')";
$balance = $this->cm->get();
最佳答案
我猜类似的东西可以完成工作。
$monthBalance = [];
foreach($balance as $entry){
$month = intval(substr($entry['monthyear']),6,7));
$monthBalance[$month] = $entry;
}
//so there is [1=>obj(), 2=>obj(), 5=>obj] in it
$value = [];
for($m = 1; $m <= 12; $m++) {
//if the balance month currently exists in the DB results
if( isset($monthBalance[$m]) ){
$value[] = $monthBalance[$m]->amount;
} else {
$value[] = 0;
}
}
关于PHP 数据形成与具有某些现有值的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48452247/