我如何避免这里的嵌套循环?使用PHP

时间:2019-06-02 13:43:46

标签: php loops nested

我在这里有一个循环,我想做的是将每年和每个季度的所有这些项保存到我的数组中,这样我就可以获得每个季度的平均值,但是这样做似乎对我不利。而且我无法等待这样做

这里所做的是从我的jason数组中读取季度和年份,并将其保存到我的12个元素数组的每个元素中。但我很确定它不好。

foreach($Jarray as $obj) {
    if ($obj->quarter == "1" and $obj->year == "2015" ) {
        $tarray[0] = $tarray[0] + $obj->sales;

    }
    if ($obj->quarter == "2" and $obj->year == "2015" ) {
        $tarray[1] = $tarray[1] + $obj->sales;
    }
    if ($obj->quarter == "3" and $obj->year == "2015" ) {
        $tarray[2] = $tarray[2] + $obj->sales;

    }
    if ($obj->quarter == "4" and $obj->year == "2015" ) {
        $tarray[3] = $tarray[3] + $obj->sales;

    }
    if ($obj->quarter == "1" and $obj->year == "2016" ) {
        $tarray[4] = $tarray[4] + $obj->sales;

    }
    if ($obj->quarter == "2" and $obj->year == "2016" ) {
        $tarray[5] = $tarray[5] + $obj->sales;

    }
    if ($obj->quarter == "3" and $obj->year == "2016" ) {
        $tarray[6] = $tarray[6] + $obj->sales;

    }
    if ($obj->quarter == "4" and $obj->year == "2016" ) {
        $tarray[7] = $tarray[7] + $obj->sales;

    }
    if ($obj->quarter == "1" and $obj->year == "2017" ) {
        $tarray[8] = $tarray[8] + $obj->sales;

    }
    if ($obj->quarter == "2" and $obj->year == "2017" ) {
        $tarray[9] = $tarray[9] + $obj->sales;

    }
    if ($obj->quarter == "3" and $obj->year == "2017" ) {
        $tarray[10] = $tarray[10] + $obj->sales;

    }
    if ($obj->quarter == "4" and $obj->year == "2017" ) {
        $tarray[11] = $tarray[11] + $obj->sales;

    }
    $count ++;
}

1 个答案:

答案 0 :(得分:0)

最简单的方法是使用年份和季度来计算元素的偏移量...

$offset  = (($obj->year-2015)*4)+$obj->quarter-1;

因此,对于2015年第1季度-这给出了0,2017年第4季度给出了11。因此代码归结为...

$tarray = array_fill(0,12,0);
foreach ( $Jarray as $obj ) {
    $offset  = (($obj->year-2015)*4)+$obj->quarter-1;
    $tarray[$offset] += $obj->sales;
}