如何从多维数组输出值

how to output values from multidimensional array

我有一个如下所示的数组:

Array
(
    [date] => Array
        (
            [0] => 01-05-2121
            [1] => 02-05-2121
        )

    [starttime] => Array
        (
            [0] => 08:00 // starttime from 01-05-2121
            [1] => 12:00 // starttime from 02-05-2121
        )

    [endtime] => Array
        (
            [0] => 10:00 // endtime from 01-05-2121
            [1] => 16:00 // endtime from 02-05-2121
        )

    [hours] => Array
        (
            [0] => 2 // total hours from 01-05-2121
            [1] => 4 // total hours from 02-05-2121
        )

)

我想创建这样的输出:

date        starttime    endtime   hours
01-05-2121  08:00        10:00     2
02-05-2021  12:00        16:00     4     

所有输入数据都通过jQuery/ajax序列化到php文件

echo("<pre>".print_r($_POST,true)."</pre>"); 向我展示了这个数组(上图)。

我的 foreach 循环应该如何创建预期的输出? 我已经这样做了:

$dates = $_POST['date']; // array of dates
foreach($dates as $date) {
    echo $date.'<br />';
}
$starttimes = $_POST['starttime'] // array of starttimes
foreach($starttimes as $starttime) {
    echo $starttime.'<br />';
}
$endtimes = $_POST['endtime'] // array of endtimes
foreach($endtimes as $endtime) {
    echo $endtime.'<br />';
}
$hours = $_POST['hours'] // array of hours
foreach($hours as $hour) {
    echo $hours.'<br />';
}

但是这些是完全分开的,starttimeendtimehours 必须绑定到每个 date

密钥匹配,所以只需循环一个并使用密钥:

foreach($_POST['date'] as $key => $date) {
    echo $date . "<br />" .
         $_POST['starttime'][$key] . "<br />" .
         $_POST['endtime'][$key] . "<br />" .
         $_POST['hours'][$key] . "<br />";
}

如果你想显示一个 table 与预期输出完全一样并且 $dates、$starttimes、$endtimes 和 $hours 的大小相同那么你可以简单地这样做-

echo "<table>" .
  "<tr>" .
    "<th>date</th>" .
    "<th>starttime</th>" .
    "<th>endtime</th>" .
    "<th>hours</th>" .
  "</tr>";
foreach($_POST['date'] as $key => $date) {
      echo "<tr><td>". $date . "</td><td>" .
      $_POST['starttime'][$key] . "</td><td>" .
      $_POST['endtime'][$key] . "</td><td>" .
      $_POST['hours'][$key]."</td><td>" .
      "</tr>";
}
echo "</table>";