0

现在我有一组ifelseif来设置 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
    }

}

?>

我会这样称呼它<?php divHeight(88,$number);?>

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

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

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

echo $newHeight;
4

1 回答 1

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;
于 2012-04-11T06:34:31.537 回答