将多个CodeIgniter结果集合并到一个数组中

2022-09-01 00:00:00 foreach php resultset codeigniter

从数据库查询的数据。

year 2021 = [
    {
        "month": 1,
        "total": "1,482"
    },
    {
        "month": 2,
        "total": "5,422"
    },
]

year 2020 = [
    {
        "month": 1,
        "total": "2,482"
    },
    {
        "month": 2,
        "total": "6,422"
    },
    {
        "month": 3,
        "total": "7,422"
    },
    .........
    {
        "month": 12,
        "total": "20,422"
    },
]
在这里,我创建了一个名为`GetData()的方法,我根据一年中的月份创建了一个从1到12的循环。接下来,我希望将数据合并到数组中,但如何合并数据?

下面是我的控制器模型,它用不同的参数反复调用相同的模型方法:

public function GetData(){
    $thn_now = 2021; 
    $thn_before = 2020; 
    $bulan = array();
    for ($bul = 1; $bul <= 12; $bul++) {
        $sql = $this->My_model->model_month($bul,$thn_now)->result();  // Here I make the current year parameter
        // $sql2 = $this->My_model->model_month($bul,$thn_before)->result();  //here are the parameters of the previous year
        foreach($sql as $row) {
            $bulan[] = array(
                'bulan' => $bul,
                'total_now' => $row->hasil,
                // how to display the previous year's total in an array ?
                // 'total_before' => $row->hasil,
            );
        }
    }
    $this->set_response($bulan,200);  
}

我想要这样的输出:

[
    {
        "month": 1,
        "total_now": "1,482"
        "total_before": "2,482"
    },
    {
        "month": 2,
        "total_now": "5,522"
        "total_before": "6,422"
    },
    {
        "month": 3,
        "total_now": null 
        "total_before": "7,422"
    },
    .........
    {
        "month": 12,
        "total_now": null,
        "total_before": "20,422"
    },
]

2021年合计只到02月,2020年合计到第12个月。

如果2021年仅到02月,则下一个数组为总计null


解决方案

我相信这将帮助您开发解决方案。我还没有包括整个$Year_2020,但我希望您能明白-

$year_2021 = [
   [
    "month" => 1,
    "total_now" => "1,482"
   ],
   [
    "month" => 2,
    "total_now" => "5,422"
   ]
  ];

  $year_2020 = [
   [
    "month" => 1,
    "total_before" => "2,482"
   ],
   [
    "month" => 2,
    "total_before" => "6,422"
   ],
   [
    "month" => 3,
    "total_before" => "7,422"
   ]
  ];

  $output = [];

  foreach ($year_2021 as $obj) {
     $key = $obj['month'];
     $output[$key] = $obj;
  }

 foreach ($year_2020 as $obj) {
    $key = $obj['month'];
    if (isset($output[$key])) {
      $output[$key]['total_before'] = $obj['total_before'];
    } else {
      $obj['total_now'] = null;
      $output[$key] = $obj;
    }
   }

    $output = array_values($output);
    error_log(json_encode($output));

输出

[{"month":1,"total_now":"1,482","total_before":"2,482"},{"month":2,"total_now":"5,422","total_before":"6,422"},{"month":3,"total_before":"7,422","total_now":null}]

相关文章