Home > Back-end >  Convert array of dates to diffrent view
Convert array of dates to diffrent view

Time:08-22

What is the fastest way to convert an array from this:

$from = [
            ['date' => '01-2017', 'income' => 0],
            ['date' => '02-2017', 'income' => 0],
            ['date' => '03-2017', 'income' => 0],
            ['date' => '01-2018', 'income' => 0],
            ['date' => '02-2018', 'income' => 0],
            ['date' => '01-2019', 'income' => 0],
        ];

to this:

        $to = [
            '1' => [
                ['date' => '01-2017', 'income' => 0],
                ['date' => '01-2018', 'income' => 0], 
                ['date' => '01-2019', 'income' => 0]
            ],
            '2' => [
                ['date' => '02-2017', 'income' => 0],
                ['date' => '02-2018', 'income' => 0],
            ],
            '3' => [
                ['date' => '03-2017', 'income' => 0],
            ]
        ];

As you can see in the result array entries are grouped by months. I have no idea how can I achieve this.

CodePudding user response:

Iterate over the array and use the month as key for the new array.

foreach ($from as $array) {
    [$month] = explode('-', $array['date']);
    $to[(int) $month][] = $array;
}

CodePudding user response:

You can try with de below solution

$to = array()
for ($i=1; $i<32; $i  ) {
  $to[(int) $i] = array_filter($from, function($el) {
    $month = (int) explode('-', $el['date'])[0]
    return $month == $i
  })
}
  • Related