php - 如何在 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"
解决方案
在使用之前尝试初始化$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;
}
推荐阅读
- multi-tenant - 尝试在数据库迁移时使用 ABP 框架创建数据库
- imagemagick - 使用蒙版制作透明区域
- encryption - OpenPGP加密中的私钥存储问题
- html - Excel 函数可以识别粗体文本吗?
- azure - 我应该如何在 Azure 中为我的应用程序实施健康检查?
- python - matplotlib:为所有图形设置单个标题(不是子图)
- javascript - konvajs 中的克隆组
- amazon-web-services - 无法将包含在 Pytorch 中编码的图像分类模型的 Flask 应用程序托管到免费套餐 AWS EC2 实例
- javascript - 如何使用 OnChange 将数据从 javascript 传输到 php
- python - python - 使附加的 y 轴(寄生虫轴)在我的图表上可见