Php如何循环两个数组

wbrvyc0a  于 2023-01-08  发布在  PHP
关注(0)|答案(1)|浏览(133)

我在正确返回数组时遇到了问题。根据我的代码,我可以返回如下:

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

但我打算返回如下:

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

在粘贴代码之前,请允许我解释一下,我有两个从数据库生成的数组,值是使用内爆存储的,我用它来把它转换成一个数组,数组一起工作意味着"time_slot": "20:22""slot": "9"是一起的,比如说$time_slot = ["05:42", "20:22"]$slot = ["12", "9"]。我正在获取当前时间以循环通过$time_slot,以便只返回大于当前时间的数组$time_slot,这对于此操作非常有效,但我希望它同时循环$time_slot$slot,因为它们如上述数组所述一起工作。

$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,                       
    );
}
pprl5pva

pprl5pva1#

您需要索引$slot,而不是使用整个数组。

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

相关问题