Home > OS >  Php how to loop two arrays
Php how to loop two arrays

Time:01-07

I am having an issue returning the array of rightly. Based on my code I was able to return as below:

[
   {    
        "time_slot": "05:42",
        "slot": ["12","9"],
   }
   {    
        "time_slot": "20:22",
        "slot": ["12","9"],
   }
]

but I intend to return as below:

[
   {    
        "time_slot": "05:42",
        "slot": "12",
   }
   {    
        "time_slot": "20:22",
        "slot": "9",
   }
]

Before I paste my code let me explain a little about it, so I have two arrays generated from the database and the value was stored with implode, which I'm using to convert it to an array. The array works together meaning "time_slot": "20:22" is together with "slot": "9". So let's say my $time_slot = ["05:42", "20:22"] and $slot = ["12", "9"]. I am getting the current time to loop through the $time_slot so as to return only array $time_slot that is greater than the current time which works perfectly for this but I want it to loop for both $time_slot and $slot as they work together as stated in above array.

$time_slot = ["05:42", "20:22"];
$slot = ["12", "9"];
$current_time = date('H:i');

$current_time = new \DateTime($current_time);
foreach ($time_slot as &$value) {

    if ($current_date == $_GET['day']) {

        if ($current_time > new \DateTime($value)) $value = null;
    }

}
$time_slot = array_filter($time_slot);

foreach ($time_slot as $sloted) {
    $IAM_ARRAY[] = array(
        'time_slot' => $sloted,
        'slot' => $slot,                       
    );
}       

CodePudding user response:

You need to index $slot rather than using the entire array.

foreach ($time_slot as $i => $sloted) {
    $IAM_ARRAY[] = [
        'time_slot' => $sloted,
        'slot' => $slot[$i],
    ];
}
  • Related