我不明白的主題是“Hello”打印一次。另一個 Foreach“Earth”打印兩次。我不明白問題出在哪里。當我卸載 Foreach 時,問題消失了,但當我再次輸入 foreach 時,問題又出現(xiàn)了<div class="carousel-clip" data-jcarousel="true" style="width: 874.798px;"><ul class="carousel-list" style="left: 0; top: 0;"><?php foreach (YoutubeApi::getAllVideo('brhhkavxkgU') as $item): ?><p>Hello</p><?php endforeach; ?></ul></div><!-- end .carousel-clip --><div class="loop-content switchable-view grid-small" data-view="grid-small" data-ajaxload="1"><div class="nag cf"><?php foreach (YoutubeApi::getAllVideo('brhhkavxkgU') as $item): ?><p>world</p><?php endforeach; ?></div></div>class YoutubeApi{public static function getAllVideo($videoId) { $url = "https://www.googleapis.com/youtube/v3/videos"; static $all = []; $params = [ 'key' => '...', 'part' => 'statistics,snippet', 'id' => $videoId, ]; $call = $url . '?' . http_build_query($params); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $call); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); curl_setopt($ch, CURLOPT_POST, false); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20); curl_setopt($ch, CURLOPT_TIMEOUT, 20); curl_setopt($ch, CURLOPT_MAXREDIRS, 10); $output = curl_exec($ch); $data = NULL; $data = json_decode($output, true); $all[] = $data; curl_close($ch); return $all; }}
1 回答

千萬里不及你
TA貢獻1784條經(jīng)驗 獲得超9個贊
這是因為你的數(shù)組$all
被聲明為靜態(tài)的,這意味著第二次運行時,第一個結果仍然存在于數(shù)組中。每次調用該函數(shù)時,它都會將新結果添加到數(shù)組中$all
。
如果這不是所需的行為,則每次都需要清除數(shù)組,或者不在函數(shù)中將其聲明為靜態(tài)。
或者,如果這是所需的行為,但您想要多次顯示結果,請更改調用代碼以檢索結果,然后對它們進行 foreach,而不是將函數(shù)調用作為顯示循環(huán)的一部分。
- 1 回答
- 0 關注
- 138 瀏覽
添加回答
舉報
0/150
提交
取消