php - Group week names based on start and end time -
i have array this
array( [mon] => array ( [start] => 09 [end] => 18 [hours] => 9 ) [tue] => array ( [start] => 09 [end] => 18 [hours] => 9 ) [wed] => array ( [start] => 09 [end] => 18 [hours] => 9 ) [thu] => array ( [start] => 09 [end] => 18 [hours] => 9 ) [fri] => array ( [start] => 00 [end] => 21 [hours] => 21 ) [sat] => [sun] => );
now task able display in simple format like
mon-thu fri 09 - 18 00-21
so how can transform above array simple array display required format @ client
i tried following code, giving dates group by,
$workhours = $bhr->workinghours; $days = array_keys($workhours); $workhoursinfo = array_values($workhours); $result = array(); for($i=0;$i<count($workhoursinfo);$i++){ $info1 = $workhoursinfo[$i]; if(empty($info1)) continue; for($j=1;$j<count($workhoursinfo);$j++) { $info2 = $workhoursinfo[$j]; if(empty($info2)) continue; if($info1['start'] === $info2['start'] && $info1['end'] === $info2['end']) { if(!in_array($days[$i],$result)) { $result[] = $days[$i]; } } } }
here function can you. i've added comments did.
$workhours = array( 'mon' => array('start' => '09', 'end' => '18', 'hours' => '9'), 'tue' => array('start' => '09', 'end' => '18', 'hours' => '9'), 'wed' => array('start' => '09', 'end' => '18', 'hours' => '9'), 'thu' => array('start' => '09', 'end' => '18', 'hours' => '9'), 'fri' => array('start' => '00', 'end' => '21', 'hours' => '21'), 'sat' => array(), 'sun' => array(), ); function format_workhours($workhours){ $days = array_keys($workhours); $temp = array(); // group start , end hours foreach($workhours $day => $hours){ if(isset($hours['start'])){ $temp[$hours['start'] . '-' . $hours['end']][] = $day; } } // echo , or - foreach($temp $i => $work){ $first = reset($work); // 1 day print if (count($work) === 1){ echo $first . ': ' . $i . '<br>'; continue; } $pos = array_search($first,$days); $array = array_slice($days,$pos,count($temp[$i])); // days follow on each other use dash if($temp[$i] === $array){ $last = end($work); echo $first . '-' . $last . ':' . $i . '<br>'; }else{ // print days comma $workdays = implode(',',$work); echo $workdays . ':' . $i . '<br>'; } } } format_workhours($workhours);
output:
mon-thu:09-18
fri: 00-21
Comments
Post a Comment