如何在一个数组PHP中比较值?

时间:2014-03-20 16:35:00

标签: php

我有以下数组结构。我想在数组中获取最大值,如果数组中的值相同则取消设置此数组。

   Array(

        [499670] => Array
            (
                [499670] => 1299.00
                [503410] => 1299.00
                [528333] => 1299.00
                [645862] => 0.00
            )

        [499671] => Array
            (
                [499671] => 1149.00
                [503408] => 1149.00
                [528329] => 1500.00
                [645858] => 0.00
            )

        [499672] => Array
            (
                [499672] => 0.00
                [503406] => 0.00
                [528324] => 0.00
                [645850] => 0.00
            )
)

我想得到以下结果

   Array(

                [499670] => 1299.00 >>> one of values in first array
                [528329] => 1500.00 >>> max value in second array
                {third array was removed, because all values are same}

)

1 个答案:

答案 0 :(得分:3)

遍历您的数组,使用array_unique()检查所有值是否相同。如果没有,请使用max()找到最大值:

$result = array();

foreach ($data as $key => $subarr) {
    if (count(array_unique($subarr)) === 1) {
        unset($data[$key]);
    } else {
        $result[] = max($subarr);
    }
}

print_r($result);

输出:

Array
(
    [0] => 1299.00
    [1] => 1500.00
)

Demo