我有GDP的数字,包括名义和购买力平价。结构是国家,名义,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 :(得分: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.';
}