Home > Software engineering >  Group array php and count
Group array php and count

Time:11-16

$data = [
     [
       id: '1',
       date_created: '2021-11-14T23:22:53.558225 00:00',
     ],
     [
       id: '2',
       date_created: '2021-11-14T23:22:00.558225 00:00',
     ],
     [
       id: '3',
       date_created: '2021-11-15T11:22:53.558225 00:00',
     ],
]

Help to get a new array, you need to group by date and count the number of resulting arrays starting from the first day.Here is an example of a new array

$new_array = [0,0,0,0,0,0,0,0,0,0,0,0,0,2,1]

CodePudding user response:

I suppose it can be done with a loop

<?php 
$data = [
     [
       'id' => '1',
       'date_created' => '2021-11-14T23:22:53.558225 00:00',
     ],
     [
       'id' => '2',
       'date_created' => '2021-11-14T23:22:00.558225 00:00',
     ],
     [
       'id' => '3',
       'date_created' => '2021-11-15T11:22:53.558225 00:00',
     ],
];

$res = array();
foreach($data as $row) {
    if(!isset($res[gmdate('d', strtotime($row['date_created']))]))
        $res[gmdate('d', strtotime($row['date_created']))] = 0;
    // array index, (current date of month) gmdate('d', strtotime($row['date_created'])) 
    $res[gmdate('d', strtotime($row['date_created']))]  ;
}
print_r($res);
  •  Tags:  
  • php
  • Related