PHP code to convert numbers (0-23) to AM/PM time format
P粉009828788
P粉009828788 2023-12-24 19:03:07
0
4
432

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粉009828788
P粉009828788

reply all(4)
P粉353282123

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粉600402085
$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粉353282123

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粉276064178

This is the code

$hrs = 15;
echo date("h a", strtotime("00-00-00 $hrs:00:00"));
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!