2011-04-09 81 views
1

這可能是一個真正簡單的問題,但我正在尋找在特定多維數組上找到數據的最有效的內存方式。在多維數組上運行計算?

陣列的一個例子:

[0] => Array(
    [fin] => 2 
    [calc] => 23.34 
    [pos] => 6665 
) 
[1] => Array(
    [fin] => 1 
    [calc] => 25.14 
    [pos] => 4543 
) 
[2] => Array(
    [fin] => 7 
    [calc] => 21.45 
    [pos] => 4665 
) 

我需要識別下面的事情的值的方法,包括:

  • 的最大 '計算值'
  • 的MIN '計算'
  • 最大'pos'
  • min'pos'
  • (你得到的要點)

我能想到的,通過每個值手動循環和調整的整數。只有這樣,因此,例如:

function find_lowest_calc($arr) { 
    $int = null; 
    foreach($arr['calc'] as $value) { 
     if($int == null || $int > $value) { 
      $int = $value; 
     } 
    } 
    return $int; 
} 

等的方法的明顯缺點,這是我將不得不爲數組中的每個值創建一個新函數(或者至少實現一個參數來更改數組鍵),並且它會通過循環遍歷整個數組3次或更多次來減慢應用程序的速度,以獲取值。原始數組可能有超過一百個值。

我會假設將有一個內部函數來收集所有(例如)'calc'值到一個臨時單個數組中,所以我可以使用它的最大值函數。

任何想法?

+0

組裝中的代碼!那會非常有效率。 – 2011-04-09 16:43:19

+0

忽略以前的評論。不能說關於內存效率,但你可以概括你的功能,像這樣'find($ arr,$ bool_min_or_max,$ key)' – 2011-04-09 16:48:04

回答

0

你是如何接收數組?如果這是你的代碼即創建數組,你可以計算出最大值和最小值,你在數據值來讀取:

$minCalc = null; 
$arr = array(); 
for(...){ 

    //read in 'calc' value 
    $subArr = array(); 
    $subArr['calc'] = //... 
    if ($minCalc === null || $minCalc > $subArr['calc']){ 
    $minCalc = $subArr['calc']; 
    } 

    //read in other values 
    //... 

    $arr[] = $subArr; 
} 

而且,在你的find_lowest_calc功能,您應該使用三重等號運算符( ===)以確定$int變量是否爲空。這是因爲如果$int等於0,則由於null等於0轉換爲整數時,語句$int == null也會返回true。

+0

道歉爲延遲接受。我從來沒有想過這樣做。該數組在系統中編譯,因此我可以輕鬆地在同一個循環中執行計算。好大聲!謝謝。 – 2011-04-10 21:57:24

1

除了一次計算所有三個值之外,沒有辦法加快速度。原因是你總是需要遍歷數組來查找子數組。即使你發現了一個bultin函數,時間複雜度也是一樣的。實現真正改變的唯一方法是使用另一個數據結構(即,不是任何布丁,但是你自己寫的)。

2
$input = array(
    array(
     'fin' => 2 
     'calc' => 23.34 
     'pos' => 6665 
    ), 
    array(
     'fin' => 1 
     'calc' => 25.14 
     'pos' => 4543 
    ), 
    array(
     'fin' => 7 
     'calc' => 21.45 
     'pos' => 4665 
    ) 
); 

$output = array(
    'fin' => array(), 
    'calc' => array(), 
    'pos' => array(), 
); 
foreach ($input as $data) { 
    $output['fin'][] = $data['fin']; 
    $output['calc'][] = $data['calc']; 
    $output['pos'][] = $data['pos']; 
} 

max($output['fin']); // max fin 
max($output['calc']); // max calc 
min($output['fin']); // min fin 
0

您不必箱每個值的新功能,只是通過你在函數

function find_lowest($arr, $indexkey) { 
    $int = null; 
    foreach($arr[$indexkey] as $value) { 
     if($int == null || $int > $value) { 
      $int = $value; 
     } 
    } 
    return $int; 
} 

由於PHP想關鍵是沒有類型安全,你應該罰款傳球字符串或詮釋索引