使用具有一些现有值的数组形成PHP数据

时间:2018-01-25 21:33:45

标签: php mysql arrays codeigniter codeigniter-3

假设我有这样的价值

Array
(
    [0] => stdClass Object
        (
            [amount] => 4000.00
            [monthyear] => 2018-02
        )

    [1] => stdClass Object
        (
            [amount] => 5000.00
            [monthyear] => 2018-01
        )
)

我想生成像这样的值

[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();

1 个答案:

答案 0 :(得分:0)

我想这样的事情。

$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;

    }
}