0

我想知道是否有更简单的方法来执行以下代码中演示的操作。此代码的目标是识别来自 $fat_values 数组的高、低、中值。代码在编写时运行正常,但我希望有一种更简洁的方法来识别中等脂肪值。

关于数据的一句话 - 允许值有 2 个相同的值,尽管有时所有 3 个值都是唯一的。当两个值相同时,一个显示为高脂肪,另一个显示为中脂肪。当 2 个值相同时,第三个值始终为 0(由此处未显示的验证规则强制执行)。

#---test with unique values---
$fat_values = array(7, 0, 4);
// $fat_values = array(7, 4, 0);

#---test with 2 values the same---
// $fat_values = array(0, 40, 40);
// $fat_values = array(40, 40, 0);

#calculations
$fat_low = min($fat_values);
$fat_high = max($fat_values);

$lowhigh = array($fat_low, $fat_high);

//loop through $fat_values - if element matches one in $lowhigh array remove it from $fat_values and from $lowhigh arrays; this will leave 1 element in $fat_values at the end

foreach ($fat_values as $key => $value):
if (in_array($value, $lowhigh)):
    unset($fat_values[$key]);
    foreach ($lowhigh as $k => $v):
        if ($k = array_search($value, $lowhigh)):
            unset($lowhigh[$k]);
        endif;
    endforeach;
endif;
endforeach;

//for remaining element in $fat_values[key], key can be 0 or 1 or 2 so copy value to a new variable to eliminate dealing with key
foreach ($fat_values as $key=>$value):
    $a = $value;
endforeach;

$fat_medium = $a;

#display results
echo "<pre>" . print_r($fat_values,1) . "</pre>";
echo 'high ' . $fat_high . '<br>';
echo 'low ' . $fat_low . '<br>';
echo 'medium ' . $fat_medium . '<br>';
4

2 回答 2

0
$fat_low = min($fat_values); // get the lowest
$fat_high = max($fat_values); // get the highest
$fat_mid = array_uniq($fat_values); // set mid wchich we gonna filter and make array unique (no doubles)

// array_search gives the key of matching the value for low
unset( $fat_mid[ array_search($fat_low, $fat_mid) ]);
// array_search gives the key of matching the value for high
unset( $fat_mid[ array_search($fat_high, $fat_mid) ]); 

if (count($fat_mid)===0){ $fat_mid = 0;} // no left, give it 0
else{ $fat_mid = current($fat_mid); }// get frist (and remaining) value
于 2013-08-08T16:50:37.040 回答
0
$arr = array(6, 5, 5);
$cnt = array_count_values($arr);
$keys = array('fat_high', 'fat_medium', 'fat_low');
if (count($cnt) < 3){
    $cnt = array_flip($cnt);
    ksort($cnt);
    $arr = array(end($cnt), end($cnt), 0);
} else {
    rsort($arr);
}
$arr = array_combine($keys, $arr);

输出:

Array
(
    [fat_high] => 5
    [fat_medium] => 5
    [fat_low] => 0
)
于 2013-08-08T20:52:09.747 回答