2016-01-22 82 views
0

我有以下功能避免不確定的偏移誤差

function getSum($array){ 
    if(is_array($array)) { 
     $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array)); 
     $sum = 0; 
     foreach ($iterator as $key => $value) { 
      $sum += $value; 
     } 
    } else{ 
     $sum = $array; 
    } 
    return $sum; 
} 

而且我使用它像這樣

$teams = array(); 
$teams[1]['AREA I']['blue'] = 30; 
$teams[1]['AREA I']['green'] = 25; 
$teams[1]['AREA II']['blue'] = 15; 
$teams[2]['AREA I']['blue'] = 40; 

echo getSum($teams); //output: 110 
echo getSum($teams[1]); //output: 70 
echo getSum($teams[1]['AREA I']); //output: 55 
echo getSum($teams[1]['AREA I']['blue']); //output: 30 

如何避免錯誤未定義偏移使用像getSum($teams[2]['AREA IV'](關鍵領域IV不是當組)?在這種情況下,我希望該函數返回零。

+1

添加一個檢查,如果offset設置與否。視情況而定'isset'或'empty'。 –

+1

要添加到@Sougata所說的內容中,可以使用''trim'](http://php.net/manual/en/function.trim.php)和'empty'。 – Script47

+1

[未定義的偏移PHP錯誤]的可能重複(http://stackoverflow.com/questions/2508215/undefined-offset-php-error) –

回答

1

由於錯誤發生在調用getSum函數之前,因此您無法更改該函數以使其可行。

但是,如果您願意更改傳遞給getSum的參數,則可以解決該問題。您可以傳遞數組而不需要其他鍵規範(以避免潛在錯誤)並將鍵指定爲第二個參數。然後把它留給getSum試圖讓該值如果它存在,就像這樣:

function getSum($array, $path = array()){ 
    // process second argument: 
    foreach ($path as $key) { 
     if (!is_array($array) || !isset($array[$key])) { 
      return 0; // key does not exist, return 0 
     } 
     $array = $array[$key]; 
    } 
    if(is_array($array)) { 
     $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array)); 
     $sum = 0; 
     foreach ($iterator as $key => $value) { 
      $sum += $value; 
     } 
    } else{ 
     $sum = $array; 
    } 
    return $sum; 
} 

$teams = array(); 
$teams[1]['AREA I']['blue'] = 30; 
$teams[1]['AREA I']['green'] = 25; 
$teams[1]['AREA II']['blue'] = 15; 
$teams[2]['AREA I']['blue'] = 40; 

// pass an optional 2nd argument:  
echo getSum($teams); //output: 110 
echo getSum($teams, [1]); //output: 70 
echo getSum($teams, [1,'AREA I']); //output: 55 
echo getSum($teams, [1,'AREA I','blue']); //output: 30 
echo getSum($teams, [2, 'AREA IV']); // no error, output: 0 
+0

感謝您的豐富答案!它的工作完美。 – lingo

+0

不客氣。 – trincot