0

我有一个多维数组,它是这样的:

Array
(
    [Monday] => Array
        (
            [open] => 05.00 PM
            [close] => 04.00 PM
            [state] => 0
        )

    [Tuesday] => Array
        (
            [open] => 
            [close] => 
            [state] => 1
        )

    [Wednesday] => Array
        (
            [open] => 03.00 AM
            [close] => 06.00 PM
            [state] => 0
        )

    [Thursday] => Array
        (
            [open] => 
            [close] => 
            [state] => 1
        )

    [Friday] => Array
        (
            [open] => 05.00 PM
            [close] => 03.00 PM
            [state] => 0
        )

    [Saturday] => Array
        (
            [open] => 05.00 PM
            [close] => 06.00 PM
            [state] => 0
        )

    [Sunday] => Array
        (
            [open] => 
            [close] => 
            [state] => 1
        )

) 

使用这个数组我想创建这样的输出:

Monday       - 05.00 PM - 04.00 PM
Tuesday      - Closed
Wednesday    - 03.00 AM - 06.00 PM
Thursday     - Closed
Friday       - 05.00 PM - 03.00 PM
Saturday     - 05.00 PM - 06.00 PM
Sunday       - Closed

我尝试了 2 个 foreach 循环,但我无法让它显示预期的输出。

foreach ($result as $days => $values) {
    echo "$days";
    foreach ($values as $k) {
        echo " - $k";
    }
    echo "<br/>";
}

它的输出类似于:

Monday - 05.00 PM - 04.00 PM - 0
Tuesday - - - 1
Wednesday - 03.00 AM - 06.00 PM - 0
Thursday - - - 1
Friday - 05.00 PM - 03.00 PM - 0
Saturday - 05.00 PM - 06.00 PM - 0
Sunday - - - 1

谁能告诉我我该如何解决这个问题?

注意:如果state = 0它不需要显示,state = 1它应该是Closed

4

3 回答 3

2

像这样执行 foreach 循环:

foreach ($result as $days => $values) {
    echo $days." - ";
    echo $values["state"] ? "Closed" : $values["open"]." - ".$values["close"];
    echo "<br />";
}
于 2013-09-07T14:46:56.093 回答
1

您应该检查state索引是否存在(1)或不存在(0),例如:if ($values['state'])

试试这个:

foreach ($result as $days => $values) {
    echo "$days";
    if ($values['state']) {
        echo " - Closed";
    } else {
        echo ": ".$values['open']." - ".$values['close'];
    }
    echo "<br/>";
}
于 2013-09-07T14:44:08.380 回答
1

使用 html 表执行 foreach 循环以获得正确对齐的行

$data = "<table >";
foreach($result as $day=>$value) {
    if($value["state"]==1) {
        $value = "<td colspan='3'> Closed </td>";   
    } else {
        $value = "<td> $value[open] </td><td> - </td><td> $value[close] </td>";;
    }

    $data .= "<tr><td> $day </td><td> - </td> $value</tr>";
}
$data .= "</table>";

echo $data;
于 2013-09-07T14:58:19.520 回答