我有一个这样的数组:
$pricing = array(
"2" => 8.23,
"5" => 10.97,
"10" => 13.28,
"15" => 15.40,
"20" => 18.15,
"25" => 20.36,
"30" => 22.84,
"40" => 25.60,
"50" => 28.35,
"60" => 31.89,
"70" => 36.23,
"80" => 39.40,
"90" => 42.52,
"100" => 44.75
);
我有一个变量,其客户端的值为1到100。
问题是:如果密钥本身不存在,找到下一个最大密钥的最佳和最快方法是什么?
E.g。我有一个值为12的变量,我需要得到它的价格。根据这里的阵列,价格将是15.40,因为下一个最大的关键是15。
我可以尝试找到键号'12',如果它不存在,我会添加一个(12 + 1)并再试一次,直到找到下一个键,但有没有任何功能可以做到这一点对我来说,还是更好/更快的东西?
编辑:澄清阵列的结构。
数组就像这里的例子一样。按键可以看到。
答案 0 :(得分:2)
一个简单的foreach
会做,但为了防止空数组或高于最高键的针,这里的实现也将覆盖它:
function find(array $pricing, $needle)
{
$last = null; // return value if $pricing array is empty
foreach ($pricing as $key => $value) {
if ($key >= $needle) {
return $key; // found it, return quickly
}
$last = $key; // keep the last key thus far
}
return $last;
}
$result = find($pricing, 12); // 15
$result = find($pricing, 101); // 100
$result = find([], 12); // null
答案 1 :(得分:1)
假设您正在寻找'requiredKey'并且数组按键排序
这似乎可以做你想要的。
代码:
<?php
$pricing = array(
"2" => 8.23,
"5" => 10.97,
"10" => 13.28,
"15" => 15.40,
"20" => 18.15,
"25" => 20.36,
"30" => 22.84,
"40" => 25.60,
"50" => 28.35,
"60" => 31.89,
"70" => 36.23,
"80" => 39.40,
"90" => 42.52,
"100" => 44.75
);
// What key we want...
$requiredKey = 12;
// outout in here
$foundKey = -1;
$foundValue = -1;
// always run the loop once...
do {
$foundKey = key($pricing); // store the current details
$foundValue = current($pricing);
next($pricing); // will be equal or greater
}
while ( current($pricing) !== false
&& $foundKey < $requiredKey);
echo '<pre>';
echo '<br />', 'key: ', $foundKey, ' value: ', $foundValue;
echo '</pre>';
输出:
key: 15 value: 15.4
答案 2 :(得分:0)
你的逻辑没问题,你可以用next()来做 http://php.net/manual/en/function.next.php
$search = 12;
$pricing = array(
"2" => 8.23,
"5" => 10.97,
"10" => 13.28,
"15" => 15.40,
"20" => 18.15,
"25" => 20.36,
"30" => 22.84,
"40" => 25.60,
"50" => 28.35,
"60" => 31.89,
"70" => 36.23,
"80" => 39.40,
"90" => 42.52,
"100" => 44.75
);
$result = null;
if (!isset($pricing[$search])) {
do {
} while (next($pricing) && $search > key($pricing));
$result = current($pricing);
} else {
$result = $pricing[$search];
}
echo $result;
答案 3 :(得分:-1)
如果您从数据库获得$ price,则可以找到值数据库