2011-02-08 11 views
0

私は名目とPPPの両方のGDP数値のCSVを持っています。構造はカントリー、公称、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.'; 
} 
関連する問題