Heim  >  Fragen und Antworten  >  Hauptteil

PHP-Code zum Konvertieren von Zahlen (0-23) in das AM/PM-Zeitformat

Ich habe eine Reihe von Zahlen im Bereich von 0 bis 23, wobei jede Zahl eine Zeit von Mitternacht bis 23 Uhr darstellt. Die Sortierung erfolgt in absteigender Reihenfolge nach dem Wert des Schlüssels.

22 => int 8
3 => int 7
5 => int 6

Warte. Wenn der Schlüssel des ersten Elements des Arrays beispielsweise 22 ist, möchte ich, dass die Variable $first „10PM“ ist.

Natürlich kann ich schreiben:

if(key($array)=='22'){
    $first = '10PM';
}

Aber ich muss es für jeden Schlüssel 23 Mal machen ... Gibt es einen einfacheren Weg?

P粉009828788P粉009828788274 Tage vor436

Antworte allen(4)Ich werde antworten

  • P粉353282123

    P粉3532821232023-12-26 16:57:54

    刚才复制错了

    <?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";
    }
    ?>

    Antwort
    0
  • P粉600402085

    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;

    Antwort
    0
  • P粉353282123

    P粉3532821232023-12-26 16:53:20

    我理解的

    <?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";
    }
    ?>

    Antwort
    0
  • P粉276064178

    P粉2760641782023-12-25 11:32:18

    这是代码

    $hrs = 15;
    echo date("h a", strtotime("00-00-00 $hrs:00:00"));

    Antwort
    0
  • StornierenAntwort