[英]PHP: Extract elements from array A at current key and push to array B
I'm building my first web app. 我正在构建我的第一个Web应用程序。 I'm using the openweathermap API. 我正在使用openweathermap API。 Right now I'm trying to create a 5 day forecast. 目前,我正在尝试创建5天的预测。 I want to get the current day from my array and push it plus the next 4 days to a new array. 我想从阵列中获取当前日期,并将其加上接下来的4天推入新阵列。 I'm stuck pushing 'today' to my new array 5 times. 我坚持将“今天”推送到新阵列5次。 I've tried pushing next($day_name) as well. 我也尝试过推next($ day_name)。 Here's the code. 这是代码。
$day_name = array(
1=>'Monday',
2=>'Tuesday',
3=>'Wednesday',
4=>'Thursday',
5=>'Friday',
6=>'Saturday',
7=>'Sunday');
$day_start = date('N');
foreach ( $day_name as $dk => $dv )
{
if( $dk == $day_start and current($day_name))
{
$five_days = array();
while(count($five_days) !== 5)
{
array_push($five_days, $dv);
}
break;
}
}
echo '<pre>';
print_r($five_days);
echo '</pre>';
This prints: 打印:
Array(
[0] => Sunday
[1] => Sunday
[2] => Sunday
[3] => Sunday
[4] => Sunday
)
Welcome any answers using the original script as I may need to use something similar in the future. 欢迎使用原始脚本的任何答案,因为将来我可能需要使用类似的东西。
If you want to get today and next four days, One option is using DatePeriod
如果您想今天和以后四天,一种选择是使用DatePeriod
$five_days = [];
$period = new DatePeriod (
new DateTime(),
new DateInterval('P1D'),
4
);
foreach ($period as $day)
{
$five_days[] = $day->format('l');
}
echo '<pre>';
print_r($five_days);
echo '</pre>';
This will result to: 这将导致:
Array
(
[0] => Sunday
[1] => Monday
[2] => Tuesday
[3] => Wednesday
[4] => Thursday
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.