2013-02-03 26 views
0
function get_frequencies($a) 
{ 
    $get_frequencies = array(); 
    foreach($a as $k => $v) 
    { 
    $get_frequencies[$v]++ ; //this is the line causing the error 
    } 
    return $get_frequencies; 
} 
/*Get Flip function involking and testing */   
$letter_freq = array("a" => "x", "c" => "y", "b" => "z", "d" => "y", "z" => "y"); 
$get_frequencies = get_frequencies($letter_freq); 
print_r($get_frequencies) 

繼承人錯誤即時獲取答案是正確的,但仍然出現此錯誤。林從我的函數得到一個未定義的索引錯誤

Notice: Undefined index: x in 
C:\Users\Marty2\Desktop\xampp\htdocs\lab13\array_library.php on line 
235 

Notice: Undefined index: y in 
C:\Users\Marty2\Desktop\xampp\htdocs\lab13\array_library.php on line 
235 

Notice: Undefined index: z in 
C:\Users\Marty2\Desktop\xampp\htdocs\lab13\array_library.php on line 
235 
Array ([x] => 1 [y] => 3 [z] => 1) 

回答

2

因爲您正在嘗試增加尚不存在的變量中的值。只需檢查它們是否存在,如果不存在,則將它們實例化並賦值爲零。然後你可以安全地增加他們的價值。

if (!isset($get_frequencies[$v])) 
{ 
    $get_frequencies[$v] = 0; 
} 
$get_frequencies[$v]++; 
+0

感謝您的快速回復 –