2011-02-08 69 views
0

我有一個CSV數字,包括名義值和PPP。結構是國家,名義,PPP。從用戶輸入中查找最接近的數值

實施例:

Islamic Republic of Afghanistan,560.673,998.466 
Albania,"3,616.10","7,381.00" 
Algeria,"4,477.80","7,103.61" 

用戶在標稱值GDP輸入。我想弄清楚的是,如何使用該值在CSV文件構建的數組中找到最接近的名義GDP值。一旦找到名義值,我想打印國家和PPP值。

我在一段時間內沒有編寫任何文件,所以我無法理解如何去做這件事。

回答

0
// $input_gdp is entered by user 
// $my_data is an array from the csv 
$closest = -1; 
$closest_diff = false; 
foreach($my_data as $key=>$row) { 
    // $row[0] - Country 
    // $row[1] - Nominal 
    // $row[2] - PPP 
    if($closest_diff === false) { 
     $closest = $key; 
     $closest_diff = abs($row[1] - $input_gdp); 
    } else { 
     $current_diff = abs($row[1] - $input_gdp); 
     if($current_diff < $closest_diff) { 
      $closest = $key; 
      $closest_diff = $current_diff; 
     } 
    } 
} 
if($closest > -1) { 
    echo 'The closest is ' . $my_data[$closest][0] . ' with a PPP of ' . $my_data[$closest][2] . '.'; 
} else { 
    echo 'None were found.'; 
} 
相關問題