gpt4 book ai didi

php - 如何获取数组中某些数组的值之和?

转载 作者:行者123 更新时间:2023-11-29 11:09:37 25 4
gpt4 key购买 nike

如何获得每个月的存款总额和取款总额?例如(所有一月份的总存款和总提款)来自数组。

实际上,我有一些 table (100+)。每个表都有很多记录,其中包含存款、取款和日期列字段。我必须将按日期分组的存款和取款金额相加。

确实,我得到了每张 table 的每月总存款和总提款金额。现在,我必须对所有表格中的每个月进行求和。例如,所有表的一月份存取款总额。

在我的 CI Controller 中:

$all_table_id = $this->admin_model->get_all_id();

foreach ($all_table_id as $table_id)
{
// $table_id['accountNo'] is generated table name
// e.g baby_ld_account_45456 ,baby_ld_account_12345

$tableName = "baby_ld_account_" . $table_id['accountNo'];

$single_table_monthly_data = $this->admin_model->get_monthly_data_each_table($tableName);

// print_r($single_table_monthly_data);

$all_table_monthly_data[] = $single_table_monthly_data;

print_r($monthly_data);
}

在我的 CI 模型中:

public function get_monthly_data_each_table($tableName) {
$sql = "SELECT DATE_FORMAT(`entryDate`,'%M') as Month,
SUM(`deposit`) AS `Deposit`,
SUM(`withDraw`) AS `Withdraw`
FROM $tableName
WHERE YEAR(`entryDate`) = YEAR(CURDATE())
GROUP BY DATE_FORMAT(`entryDate`,'%M')";

$query = $this->db->query($sql);
$result = $query->result_array($query);

return $result;
}

数组结果:

Array (
[0] => Array (
[0] => Array ( [Month] => January [Deposit] => 4000 [Withdraw] => 8000 )
[1] => Array ( [Month] => February [Deposit] => 200 [Withdraw] => 5000 )
)

[1] => Array (
[0] => Array ( [Month] => January [Deposit] => 1000 [Withdraw] => 1000 )
[1] => Array ( [Month] => February [Deposit] => 3000 [Withdraw] => 6000 )
)
[2] => Array (
[0] => Array ( [Month] => January [Deposit] => 6000 [Withdraw] => 2000 )
[1] => Array ( [Month] => February [Deposit] => 4000 [Withdraw] => 8000 )
)

[3] => Array (
[0] => Array ( [Month] => January [Deposit] => 3500 [Withdraw] => 2000 )
[1] => Array ( [Month] => February [Deposit] => 1200 [Withdraw] => 5000 )
)
)

谁能给我一个解决方案吗?

最佳答案

正如评论中指出的那样,最好使用 SQL 查询来完成。

但是你肯定可以用 PHP 做到这一点:

$result = array_reduce(
array_reduce($array, 'array_merge', []), // Flattern array.
function ($result, $item) {
// Extract array elements to variables, for the sake of easier use.
extract($item);

// If there's no entry for current month - create emtpy entry.
if (!isset($result[$Month])) {
$result[$Month] = [
'Deposit' => 0,
'Withdraw' => 0
];
}

// Add current amounts.
$result[$Month]['Deposit'] += $Deposit;
$result[$Month]['Withdraw'] += $Withdraw;

return $result;
},
[]
);

这里是working demo .

关于php - 如何获取数组中某些数组的值之和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40827760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com