要通過創建擴大user3720435's answer,您正在使用大量的內存每次運行該功能時都會有新的$api
變量。要理解爲什麼,我們的「展開」的代碼 - 想象這是所有寫出來的順序沒有函數調用:
$api1 = GetConectApi ($index1, offset1)-> Getrecords();
foreach ($api1 => $value1) {
// Here is my necessary loop
}
if (count ($api1) > 0) {
// RECURSION HAPPENS HERE
$index2 = $index1 + 200, $offset2 = $offset1 + 200
$api2 = GetConectApi ($index, offset)-> Getrecords();
foreach ($api2 => $value2) {
// Here is my necessary loop
}
if (count ($api2) > 0) {
// RECURSE AGAIN, AND AGAIN, AND AGAIN
}
}
請注意,我已經改名爲所有的變量爲$api1
,$api2
,等等。這是因爲每個當你運行該函數時,$api
實際上是一個不同的變量。它在源代碼中有相同的名稱,但它不代表相同的內存。
現在,PHP不知道當你創建$api2
時,你不會再使用$api1
,所以它必須保存在內存中;隨着越來越多的數據集結束,它需要越來越多的內存。
user3720435的建議是遞歸之前添加unset($api)
:
$api = GetConectApi ($index, offset)-> Getrecords();
foreach ($api => $value) {
// Here is my necessary loop
}
if (count ($api) > 0) {
unset($api);
// code as before
}
這將告訴PHP,你不需要內存了,所以它遞歸,也不會建立。您仍然會構建$index
和$offset
的多個副本,但相比之下,這些可能非常小。
所有的說法,目前尚不清楚爲什麼你需要在這裏遞歸。整個事情實際上可以改變一個簡單的循環:
do {
$api = GetConectApi ($index, offset)-> Getrecords();
foreach ($api => $value1) {
// Here is my necessary loop
}
$index = $index + $offset;
} while (count ($api) > 0)
do..while循環總是執行一次,然後不斷重複,直到條件爲假。打開它看起來是這樣的:
// do...
$api = GetConectApi ($index, offset)-> Getrecords();
foreach ($api => $value1) {
// Here is my necessary loop
}
$index = $index + $offset;
if (count ($api) > 0) { // while...
$api = GetConectApi ($index, offset)-> Getrecords();
foreach ($api => $value1) {
// Here is my necessary loop
}
$index = $index + $offset;
}
if (count ($api) > 0) { // while...
// etc
請注意,我們並不需要,因爲我們去一輪循環分配任何額外的內存,因爲我們還沒有進入一個新的功能 - 我們只是使用相同的變量一遍又一遍地。
你不是在使用緩存嗎? –
嗨,謝謝你的回答,緩存在第一次交互循環完成後對我有用,而且這個檢查每天發生一次,所以無論使用緩存,腳本每天都會運行1次,以使可能的更新日誌 –
這可能屬於[代碼審查SE](https://codereview.stackexchange.com/) –