php阵列安排

Hi i convert an collections of string comma separated 0 1 5, 2 3 15, 4 18 20 into an array using this functions as follow:

$openHrs = explode(",", $openHrs['open_hours']);

The end result are as follow:

Array ( [0] => 0 1 5 [1] => 2 3 15 [2] => 4 18 20 )

In this array 0 1 5 means Mon 1 am 5 am and 4 18 20 means Thur 6 pm 8 pm, so first digit represent weekday rest 2 digits represent hours in 24hrs format, now how can i output the existing array into this format?

Array ( [0] => Mon 1 am 5 am [1] => Tue 3 am 3 pm [2] => Thur 6 pm 8 pm )

Thanks

For the weekday, I suggest:

$weekday=array('Mon','Tue','Wed','Thu','Fri','Sat','Sun');    

foreach ($openHours As &$openHour) {
    $foo = explode(' ',$openHour);
    $openHour=$weekday[$foo].' '. // <-- write yourself a nice function to convert 24h to 12h, maybe there's something like this in PHP already?       
}

Try this:

// This will be used for the week days
$weekdays = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');

// Loop through each date
foreach($openHrs as &$temp) {
    // Separate the numbers
    $temp = explode(" ", $temp);

    // Change from a 24 hrs clock to a 12 hrs clock
    $temp[1] = $temp[1] > 12 ? $temp[1] - 12 . 'pm' : $temp[1] . 'am';
    $temp[2] = $temp[2] > 12 ? $temp[2] - 12 . 'pm' : $temp[2] . 'am';

    // Update the element
    $temp = $weekdays[$temp[0]] . ' ' . $temp[1] . ' ' . $temp[2];
}

I would use array_map to get a filtered version. You can create dates using mktime() and format them using date(). I believe this should be the solution:

$filtered = array_map(function($incoming) {
    $parts = explode(' ', $incoming);
return
    date('D', mktime(0,0,0,1, $parts[0])) . ' ' .
    date('g a', mktime($parts[1])) . ' ' .
    date('g a', mktime($parts[2]));
}, $openHrs);

I would explode each Arrayelement again with a whitespace as Delimiter so you have a better array structure:

Array ( [0] => Array(0, 1, 5), [1] => Array(1, 3, 3) [2] => Array(4, 18, 18) )

If you have this structure there are probably several approaches. There might be a solution with date() and timestamps but Iam honestly not to sure about that. An other solution would be. Define another array with the Weekdays.

$weekdays = array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");

Then you can use the numbers that you have as index for that array to output the correct weekday. The hours can you output with a little selfmade function ala:

function twentyFourHourToAmPM($number) {
    if ($number > 12) {
         return ($number - 12)." pm";
    } else {
         return $number." am";
    }
 }

Output everything should then work like this:

foreach ($openHrs as $key => $value) {
    echo $weekdays[$value[0]]." ".twentyFourHourToAmPM($value[1])." - ".twentyFourHourToAmPM($value[2]);
}