I have a PHP array like this : Pastebin Array Exemple
Each array element have a key TIME. I would like to split this array by hours.
Example :
Each array elements with key TIME between 8h – 8h59 = 1 Array
Each array elements with key TIME between 9h – 9h59 = 1 Array
Each array elements with key TIME between 10h – 10h59 = 1 Array
ETC …
And this for all hours in a day.
Could you help me with this please.
EDITED:
Now i have this that is working but i would like to have something much simple.
$sales_by_hours = array(); foreach($sales_array as $element){ $time = strtotime($element['TIME']); if ($time >= strtotime('7:00') && $time <= strtotime('7:59')){ $sales_by_hours['7:00'][] = $element; } if ($time >= strtotime('8:00') && $time <= strtotime('8:59')){ $sales_by_hours['8:00'][] = $element; } if ($time >= strtotime('9:00') && $time <= strtotime('9:59')){ $sales_by_hours['9:00'][] = $element; } if ($time >= strtotime('10:00') && $time <= strtotime('10:59')){ $sales_by_hours['10:00'][] = $element; } if ($time >= strtotime('11:00') && $time <= strtotime('11:59')){ $sales_by_hours['11:00'][] = $element; } if ($time >= strtotime('12:00') && $time <= strtotime('12:59')){ $sales_by_hours['12:00'][] = $element; } if ($time >= strtotime('13:00') && $time <= strtotime('13:59')){ $sales_by_hours['13:00'][] = $element; } }
Advertisement
Answer
Simpler than what you have would be
$sales_by_hours = array(); foreach($sales_array as $element) { // the H is 24-hour format of an hour with leading zeros - 00 through 23 $key = date('H:00', $time); // make sure the key exists in the array if(!isset($sales_by_hours[$key])) { $sales_by_hours[$key] = array(); } $sales_by_hours[$key][] = $element; }