2012-07-10 147 views
4

我正在從mysql結果中循環數千行並將它們添加到不同的數組中。如何獲取(通過引用)數組的長度

我得到數組中最後一個元素的引用來操作(因爲這個問題範圍之外的原因)。

I.e. (只是場景的一個例子)

$myarray = array(); 
$result = &$myarray; 
$row = &$result[count($result)-1] 

當然這個工作,但因爲這個線程(Why is calling a function (such as strlen, count etc) on a referenced value so slow?)解釋說:調用引用其犯規期望通過引用的變量,由於變量的函數,導致函數創建一個變量的副本來進行操作。

當我的$ result數組增長到數千個元素時,不斷調用它,導致它的拷貝,使得代碼無法使用緩慢。

我該如何解決這個問題 - 不建議不要通過引用使用變量。 另外,我不能保持單獨的rowcounters。

基本上我需要知道如何解引用一個引用變量(我知道不能做),或者其他方式來獲得數組長度? ,或者一種獲取數組中最後一行的引用的方式(無需彈出)

記住數組也可以是空的。

已經花了我很長時間才發現這是問題,所以我非常感謝任何幫助解決問題。

編輯 給大家,說數不可能比結束慢/鍵: 只要運行這個簡單的測試,以確認

//setup array of 10 000 elements 
$ar = array(); 
for ($i = 0 ; $i < 10000 ; $i++) 
{ 
    $ar[] = $i; 
} 
//get a reference to it 
$ref = &$ar; 
error_log (date("Y/m/d H:i:s")." : speed test 1 \r\n",3,"debug.log"); 
//do 10 000 counts on the referenced array 
for ($i = 0 ; $i < 10000 ; $i++) 
{ 
    $size = count($ref); 
} 
error_log (date("Y/m/d H:i:s")." : speed test 2 \r\n",3,"debug.log"); 
//do 10 000 end/key on the referenced array 
for ($i = 0 ; $i < 10000 ; $i++) 
{ 
    reset($ref); 
    end($ref); 
    $size = key($ref); 
} 
error_log (date("Y/m/d H:i:s")." : end \r\n",3,"debug.log"); 

輸出:15秒做數少...比第二次做結束/鍵

2012/07/10 17:25:38 : speed test 1 
2012/07/10 17:25:53 : speed test 2 
2012/07/10 17:25:53 : end 
+0

基本上你正在調用&$ result [int]你使用count($ result)作爲鍵嗎?我不明白你爲什麼要這樣做,你能展示更多的代碼嗎? – Pilatus 2012-07-10 12:32:32

+1

'count($ result)'不會創建$ result的副本,因爲它不會修改它。 – raina77ow 2012-07-10 12:32:54

+1

據我所見,count($ result)不會在引用上操作嗎? – cypherabe 2012-07-10 12:34:52

回答

3

我仍然不知道爲什麼這是必要的。但是,你已經索引的數組作爲數值順序排列,這樣你就可以做到這一點「把戲」來獲得尺寸:

// Make sure the array pointer is at the end of the array 
end($result); // Not sure if this is necessary based on your description 
$size = key($result) + 1; // Get the numeric key of the last array element 

注意兩個end()key()參照持有它們的參數。但是,如果他們現在使用引用的引用,我不會感到驚訝,但這是您可以調查的內容。

+0

非常感謝。奇蹟般有效。 – 2012-07-10 14:06:22

1

根據您的其他需要,你提到,但沒有descripe,也許少數人真的老校友(深層次)功能coud幫助:

end($result); // set pointer to (current) last element 
$pos = key($result); //index of the last element 
$row = &$result($pos); 

編輯:我打字太慢了:)

+0

非常感謝。只是有點太慢;)必須接受第一個正確的答案......但這正是我想要的,並解決了我的問題。 – 2012-07-10 14:07:43