Jon*_*Jon 5 php data-structures
我有一个看起来像这样的表:
<22 23-27
8-10 1.3 1.8
11-13 2.2 2.8
14-16 3.2 3.8
Run Code Online (Sandbox Code Playgroud)
它继续下去.所以我想查找这样的值:
lookup(11,25)
Run Code Online (Sandbox Code Playgroud)
并获得响应,在这种情况下2.8.用于此目的的最佳数据结构是什么?我有CSV格式的数据.
我想用PHP编程.
谢谢.
我当然不是说这是最好或最有效的数据结构,但这是我将数据映射到与原始数据非常相似的二维 PHP 数组的方式:
$fp = fopen('data.csv', 'r');
$cols = fgetcsv($fp);
array_shift($cols); // remove empty first item
$data = array();
while ($row = fgetcsv($fp)) {
list($min, $max) = explode('-', $row[0]);
// TODO: Handle non-range values here (e.g. column header "<22")
$data["$min-$max"] = array();
for ($x = 0; $x < count($cols); $x++) {
$data["$min-$max"][$cols[$x]] = $row[$x + 1];
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您需要在函数中添加一些解析逻辑lookup
:
function lookup($row, $col) {
$return = null;
// Loop through all rows
foreach ($data as $row_name => $cols) {
list($min, $max) = explode('-', $row_name);
if ($min <= $row && $max >= $row) {
// If row matches, loop through columns
foreach ($cols as $col_name => $value) {
// TODO: Add support for "<22"
list($min, $max) = explode('-', $col_name);
if ($min <= $col && $max >= $col) {
$return = $value;
break;
}
}
break;
}
}
return $return;
}
Run Code Online (Sandbox Code Playgroud)