I have an array of numbers ranging from 0 to 23, each number represents a time from midnight to 11pm. It sorts by the key's value in descending order.
22 => int 8 3 => int 7 5 => int 6
etc. For example, if the key of the first element of the array is 22, I want the variable $first to be "10PM".
Of course, I can write:
if(key($array)=='22'){ $first = '10PM'; }
But I have to do it 23 times for each key... Is there an easier way?
P粉3532821232023-12-26 16:57:54
I just copied it wrong
<?php // 原始数组 $array = [ 22 => 8, 3 => 7, 5 => 6 ]; // 转换后的时间数组 $times = []; foreach ($array as $key => $value) { // 将键值(小时)转换为12小时制的时间格式 $hour = $key % 12; if ($hour == 0) { $hour = 12; } $times[$key] = $hour . ($key >= 12 ? 'PM' : 'AM'); } // 输出转换后的时间数组 foreach ($times as $timeKey => $time) { echo "键值" . $timeKey . "对应的输出为:" . $time . "\n"; } ?>
P粉6004020852023-12-25 17:02:45
$array = array( 22 => 8, 3 => 7, 5 => 6 ); $i = 1; foreach ($array $key=>$val) { ${'time_' . $i} = date("HA", strtotime($key . ":00:00")); $i++; } //Now check echo $time_1;
P粉3532821232023-12-26 16:53:20
I understand
<?php // 原始数组 $array = [ 22 => 8, 3 => 7, 5 => 6 ]; // 转换后的时间数组 $times = []; foreach ($array as $key => $value) { // 将键值(小时)转换为24小时制的时间格式 $hour = $key % 12; if ($hour == 0) { $hour = 12; } $times[$key] = $hour . 'PM'; } // 输出转换后的时间数组 foreach ($times as $timeKey => $time) { echo "键值" . $timeKey . "对应的输出为:" . $time . "\n"; } ?>
P粉2760641782023-12-25 11:32:18
This is the code
$hrs = 15; echo date("h a", strtotime("00-00-00 $hrs:00:00"));