2

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

3
  • is the size of $dates, $starttimes, $endtimes and & hours same? Commented Aug 20, 2021 at 18:29
  • yes size of all these is the same Commented Aug 20, 2021 at 18:32
  • Okay. In that case check my answer. Commented Aug 20, 2021 at 18:35

2 Answers 2

2

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 />";
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.