在两个数组中取消设置匹配值

时间:2013-08-08 16:45:15

标签: php arrays

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

关于数据的一个词 - 允许值具有相同的2个值,但有时所有3个值都是唯一的。当2个值相同时,一个显示为高脂肪而另一个显示为中等脂肪。当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>';

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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
)
相关问题