首页 > 解决方案 > 如何在 for 循环中创建一个数组并在 forloop 之外访问该数组

问题描述

我正在尝试将for循环中的值作为数组存储,以便可以在循环之外访问它们。

foreach ($doctor->booking as $booking) {
    $bookeddate = date('Y-m-d', strtotime($booking->booked_time));

    if( $bookeddate == $end_date ) {
        $booked_time[] = date('H:i a', strtotime($booking->booked_time));
    }
}

foreach ($booked_time as $key ) {
    echo $key;
}

这段代码一直给我一个错误"Undefined variable: booked_time"

标签: phparrayslaravel

解决方案


在使用之前尝试初始化$booked_time,因为它仅在函数内部具有作用域

$booked_time = [];
foreach ($doctor->booking as $booking) {
       $bookeddate=date('Y-m-d',strtotime($booking->booked_time));
           if($bookeddate==$end_date){
             $booked_time[]=date('H:i a',strtotime($booking->booked_time));
           }
 }

 foreach ($booked_time as $key ) {
      echo $key;
 }

推荐阅读