我希望从 API 中获取一些数据并将其构建为一个多维数组,然后我可以循环并在 Twig 模板中呈现出来。我的代码几乎有效。最终数组
$forecastArr
仅包含 foreach
的最后一次迭代,而不是包含我认为 array_push(
) 会实现的每次迭代。
这是被退回的东西。理想情况下,这个最终数组将包含几天的天气数据,而不是仅包含最终迭代。
array (
0 =>
array (
'period' => 'Wednesday',
'image' => 'https://forecast.weather.gov/newimages/medium/few.png',
'text' => 'Sunny, with a high near 87.',
),
)
我的印象是我的迭代 是 工作,但我正在覆盖我的最终数组而不是附加它。
这是我目前正在运行的代码。我已经尝试了几个不同的调整,但这对我来说是伪代码方面最有意义的,所以我一直回到它......
$forecast = weatherConditions(); // The API data
$dayCount = 0;
foreach ( $forecast['time']['startPeriodName'] as $key => $period ) {
$forecastArr = array(); // Create the final array
// The idea here is that for every instance of `startPeriodName`, I create an array of relevant data, stored as $periodArr.
$periodArr = array(
"period" => $period,
'image' => $forecast['data']['iconLink'][ $dayCount ],
'text' => $forecast['data']['text'][ $dayCount ]
);
// I then take that $periodArr and push it into the main array, so I should end up with an array of arrays.
array_push( $forecastArr, $periodArr );
$dayCount++;
}
你正在(重新)初始化
$forecastArr
数组inside循环而不是在迭代之前做一次:
$forecastArr = array(); // Moved OUTSIDE the iteration
foreach ( $forecast['time']['startPeriodName'] as $key => $period ) {
// The idea here is that for every instance of `startPeriodName`,
// I create an array of relevant data, stored as $periodArr.
$periodArr = array(
"period" => $period,
'image' => $forecast['data']['iconLink'][ $dayCount ],
'text' => $forecast['data']['text'][ $dayCount ]
);
// I then take that $periodArr and push it into the main array,
// so I should end up with an array of arrays.
array_push( $forecastArr, $periodArr );
$dayCount++;
}