$_POST
is equal to:
Array
(
[time_start] => Array
(
[0] => 00:00
[1] => 02:00
)
[time_end] => Array
(
[0] => 03:00
[1] => 05:00
)
[time_teach] => Array
(
[0] => 03:00
[1] => 00:00
)
[submit] =>
)
And we are going to create the following output:
$data = [
[
"time_start" => $_POST["time_start"][0],
"time_end" => $_POST["time_end"][0],
"time_teach" => $_POST["time_teach"][0],
],
[
"time_start" => $_POST["time_start"][1],
"time_end" => $_POST["time_end"][1],
"time_teach" => $_POST["time_teach"][1],
],
];
One of my solution for this one:
<?php
foreach ($_POST["time_start"] as $i => $time_start) {
if (!isset($_POST["time_end"][$i]) ||
!isset($_POST["time_teach"][$i]) ||
// trim($_POST["time_start"][$i]) === "" ||
// trim($_POST["time_end"][$i]) === "" ||
// trim($_POST["time_teach"][$i]) === ""
) {
continue;
} else {
// $time_start = trim($time_start);
// $time_ends[$i] = trim($time_ends[$i]);
// $time_teachs[$i] = trim($time_teachs[$i]);
$row_item = [
"time_start" => $time_start,
"time_end" => $_POST["time_end"][$i],
"time_teach" => $_POST["time_teach"][$i],
];
$data[] = $row_item;
}
}
?>
I am aware it's possible to do it easily by a foreach and getting other value by foreach keys. But I am looking for the best solution. I guess maybe PHP has a built-in function that can do this job like magic!
I am looking for other ideas about this problem. Which may teach me something new.
CodePudding user response:
if you want short this statement, can you write these such:
<?php
$post = [
'time_start'=>
[
0=> '00:00',
1=> '02:00'
],
'time_end' =>
[
0 => '03:00',
1 => '05:00'
],
'time_teach' =>
[
0 => '03:00',
1 => '00:00'
]
];
array_walk($post['time_start'],function($v,$k) use (&$data,$post){
if(!isset($post['time_end'][$k])) return false;
$data[] = [
'time_start' => $v,
'time_end' => $post['time_end'][$k]
];
});
print_r($data);
CodePudding user response:
A loop variant may be
$mappedArray = [];
foreach ($_POST as $key => $times) {
foreach($times as $index => $time) {
$mappedArray[$index][$key] = $time;
}
}