PHP 数据形成与具有某些现有值的数组

标签 php mysql arrays codeigniter codeigniter-3

假设我有这样的值(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/

相关文章:

php - 用laravel在mysql中插入多维数组json

php - SQL 创建表 - 错误

mysql - 查询以获取项目计数,包括缺失数据的零

PHP 警告导致脚本在运行 FastCGI 的 IIS 上停止

php - 将mysql数据插入div

javascript - 有没有办法在标题案例方法中忽略首字母缩略词?

ruby-on-rails - 在 Rails 4 中扩展数组而不创建新类

arrays - 复合类型数组的正确语法

php - MYSQL函数和PHP函数,哪个更好?

PHP 简单 HTML DOM - 获取稀有标签内的文本