Jack Maessen
Jack Maessen

Reputation: 1864

how to output values from multidimensional array

I have an array that looks like this:

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
        )

)

I want to create an output like this:

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

All the input data is serialized via jQuery/ajax to php file

echo("<pre>".print_r($_POST,true)."</pre>"); shows me this array (above).

How should my foreach loop look like to create the expected output? I already did this:

$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 />';
}

But these are completely seperated and starttime, endtime and hours must be binded to each date

Upvotes: 2

Views: 42

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

The keys match so just loop one and use the key:

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

Upvotes: 2

Raju Ahmed
Raju Ahmed

Reputation: 354

If you want to show a table exactly like the expected output and the size of $dates, $starttimes, $endtimes and $hours are same then you can simply do this-

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

Upvotes: 0

Related Questions