首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用PHP过滤数组

使用PHP过滤数组
EN

Stack Overflow用户
提问于 2018-07-07 03:16:38
回答 1查看 42关注 0票数 0

我有这个数组:

代码语言:javascript
复制
Array
(
    [0] => Array
        (
            [DEB_Date] => 2018-01-06
            [DEB_Total] => 100.00
            [DEB_Nb_Days] => 181
        )
    [1] => Array
        (
            [DEB_Date] => 2018-07-06
            [DEB_Total] => 100.00
            [DEB_Nb_Days] => 0
        )
)

我想要一种依赖于DEB_Nb_Days的报告。

所以我的脚本如下:

代码语言:javascript
复制
// Init the array
$arr['0_to_30']['DEB_Total'] = 0;
$arr['31_to_60']['DEB_Total'] = 0;
$arr['61_to_90']['DEB_Total'] = 0;
$arr['91_to_120']['DEB_Total'] = 0;
$arr['121_and_more']['DEB_Total'] = 0;

// Loop between the debtors
foreach($debtors as $debtor){
    if($debtor['DEB_Nb_Days'] >= 0  || $debtor['DEB_Nb_Days'] <= 30) { $arr['0_to_30']['DEB_Total'] += $debtor['DEB_Total']; }
    if($debtor['DEB_Nb_Days'] >= 31 || $debtor['PAY_Nb_Days'] <= 60) { $arr['31_to_60']['DEB_Total'] += $debtor['DEB_Total']; }
    if($debtor['DEB_Nb_Days'] >= 61 || $debtor['PAY_Nb_Days'] <= 90) { $arr['61_to_90']['DEB_Total'] += $debtor['DEB_Total']; }
    if($debtor['DEB_Nb_Days'] >= 91 || $debtor['PAY_Nb_Days'] <= 120) { $arr['91_to_120']['DEB_Total'] += $debtor['DEB_Total']; }
    if($debtor['PAY_Nb_Days'] >= 121) { $arr['121_and_more']['DEB_Total'] += $debtor['DEB_Total']; }
}

我应该有这个:

代码语言:javascript
复制
$arr['0_to_30']['DEB_Total'] = 100;
$arr['31_to_60']['DEB_Total'] = 0;
$arr['61_to_90']['DEB_Total'] = 0;
$arr['91_to_120']['DEB_Total'] = 0;
$arr['121_and_more']['DEB_Total'] = 100;

但实际上结果是:

代码语言:javascript
复制
$arr['0_to_30']['DEB_Total'] = 200;
$arr['31_to_60']['DEB_Total'] = 200;
$arr['61_to_90']['DEB_Total'] = 200;
$arr['91_to_120']['DEB_Total'] = 200;
$arr['121_and_more']['DEB_Total'] = 0;

我在这里错过了什么?

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-07 03:34:10

您可以重新构造if条件集,以首先查找最高值,然后使用else减少比较次数……

代码语言:javascript
复制
foreach ($debtors as $debtor) {
    if ($debtor['DEB_Nb_Days'] >= 121) {
        $arr['121_and_more']['DEB_Total'] += $debtor['DEB_Total'];
    } 
    else if ($debtor['DEB_Nb_Days'] >= 91) {
        $arr['91_to_120']['DEB_Total'] += $debtor['DEB_Total'];
    } 
    else if ($debtor['DEB_Nb_Days'] >= 61) {
        $arr['61_to_90']['DEB_Total'] += $debtor['DEB_Total'];
    } 
    else if ($debtor['DEB_Nb_Days'] >= 31) {
        $arr['31_to_60']['DEB_Total'] += $debtor['DEB_Total'];
    } 
    else {
        $arr['0_to_30']['DEB_Total'] += $debtor['DEB_Total'];
    }
}

(这也纠正了在某些情况下,您使用PAY_Nb_Days而不是DEB_Nb_Days )。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51216498

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档