需要一些算法帮助

时间:2012-04-11 06:14:46

标签: php algorithm function

现在我有一组 if elseif 来设置div的高度

<?php
if($num == 0){echo 'height:0px;';} 
elseif($num > 0 && $num < 10) {echo 'height:3px;';} 
elseif($num >= 10 && $num < 22) {echo 'height:7px;';}
elseif($num >= 22 && $num < 45) {echo 'height:16px;';}
elseif($num >= 45 && $num < 50) {echo 'height:33px;';}
elseif($num >= 50 && $num < 67) {echo 'height:36px;';}
elseif($num >= 67 && $num < 79) {echo 'height:48px;';}
elseif($num >= 79 && $num < 88) {echo 'height:56px;';}
elseif($num >= 88) {echo 'height:72px;';}
?>

问题在于,对于5个不同的div,这被复制了5次,并且认为有更好的方法可以做到这一点

像这样:

<?php
      function divHeight($maxNum,$number)
{

    if($number == 0)
    {
      echo 'height:0px;' ;
    }

    elseif($number >= $maxNum)
    {
      echo 'height:72px;' ;
    }

    else
    {
       //here were the algorithm have to be
    }

}

&GT;

我会将其称为<?php divHeight(88,$number);?>

div的最大高度是72,现在如何计算高度?

//编辑:这很简单:X:X但为时已晚,我没有睡觉

$newHeight = floor($number * 72 / 100);

echo $newHeight;

1 个答案:

答案 0 :(得分:2)

function mapNumToHeight($num) {
    // Max $num => height for that num
    $heightMap = array(
        0 => 0,
        9 => 3,
        21 => 7,
        44 => 16,
        49 => 33,
        66 => 36,
        78 => 48,
        87 => 56,
        88 => 72
    );

    // Store the keys into an array that we can search
    $keys = array_keys($heightMap);
    rsort($keys);

    // We want to find the smallest key that is greater than or equal to $num.
    $best_match = $keys[0];
    foreach($keys as $key) {
        if($key >= $num) {
            $best_match = $key;
        }
    }

    return 'height:' . $heightMap[$best_match] . 'px;';
}

mapNumToHeight(3); // height:3px;
mapNumToHeight(33); // height:16px;
mapNumToHeight(87); // height:56px;
mapNumToHeight(88); // height:72px;
mapNumToHeight(1000); // height:72px;