簡體   English   中英

在PHP和MySQL中無法處理嵌套數組的輸出/結構

[英]Having trouble with the output/structure of a nested Array in PHP and MySQL

我試圖制作一個整齊,結構化的電影和放映時間清單。

$shows = array(
    array(
        "Thursday" => array(
            "17:00",
            "19:00")),
    array(
        "Friday" => array(
            "16:30",
            "18:45"
            "20:10")),
    array(
        "Saturday" => array(
            "18:30",
            "21:00"))
);

問題是我似乎無法以合理的方式打印出來。 在這種情況下,日子應該是充滿活力的,而不是艱難的日子。

for ($row = 0; $row < $shows.length(); $row++) //Haven't got a clue about the 'length()'
{
    print $shows[$row] . "<br>"; //Print the day.

    for (

   $col = 0; $col < $shows[$row].length(); $col++) //Loop through each day.
    {
        print (">" . $shows[$row][$col] . "<br>"); //Print each time of the day.
    }

}

我想做的是每天打印出相應的時間。 應該像這樣出來。

Thursday - 17:00
           19:00

Friday   - 16:30
           18:45
           20:10
foreach ($shows as $show) {
    foreach ($show as $day => $times) {
        echo $day;
        foreach ($times as $time) {
            echo $time;
        }
    }
}

但是,實際上,您應該這樣簡化一下:

$shows = array(
    array('day' => 'Saturday', 'times' => array('17:00', '19:00')),
    …
);

foreach ($shows as $show) {
    echo $show['day'];
    foreach ($show['times'] as $time) {
        echo $time;
    }
}

或者,以計算機可解析的方式真正正確地執行此操作:

$shows = array(
    strtotime('2010-12-24 17:00:00'),
    strtotime('2010-12-24 19:00:00'),
    …
);

$lastDate = null;
foreach ($shows as $show) {
    if (!$lastDate || date('Y-m-d', $show) != date('Y-m-d', $lastDate)) {
        echo date('l', $show);
    }
    echo date('H:i', $show);
    $lastDate = $show;
}

:o)

在PHP中,要獲取數組中元素的數量,請使用count函數。

for ($row = 0; $row < count($shows); $row++) {
        foreach($shows[$row] as $key => $vals) {
                echo "$key - ";
                $first = true;
                foreach($vals as $val) {
                        if($first) {
                                echo "\t$val\n";
                                $first = false;
                        } else {
                                echo "\t\t$val\n";
                        }
                }
        }
}

Ideone鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM