PHP从数组中获取最大值

时间:2013-08-07 10:28:49

标签: php

以下是数组的输出:

Array
(
    [0] => stdClass Object
        (
            [id_category] => 68, 67
            [cost] => 99
        )

    [1] => stdClass Object
        (
            [id_category] => 70
            [cost] => 100
        )

    [2] => stdClass Object
        (
            [id_category] => 70
            [cost] => 10
        )

)

如何使用数组仅过滤最大值?所以输出只是

Array
(

    [0] => stdClass Object
        (
            [id_category] => 70
            [cost] => 100
        )

)

感谢。

3 个答案:

答案 0 :(得分:3)

Foreach是你的朋友:

$maxObj = null;

foreach ($arr as $key => $obj) {
  if ($maxObj == null || $obj->cost > $maxObj->cost) {
    $maxObj = $obj;
  }
}

var_dump( array($maxObj) );

一般功能:

function arrayMaxCallback($arr, $cb) {
  if (count($arr) == 0) {
    return null;
  }
  $max = null;
  foreach ($max as $key => $obj) {
    if ($max == null || $cb($max, $obj)) {
      $max = $obj;
    }
  }
  return $max;
}

用例:

$maxCost = arrayMaxCallback($arr, function ($max, $new) {
  return $new->cost > $max->cost;
});

// if you still have to use PHP < 5.3
function cmpCost($max, $new) {
  return $new->cost > $max->cost;
}

$maxCost = arrayMaxCallback($arr, 'cmpCost');

答案 1 :(得分:1)

$max = -999;
$max_obj = NULL;

foreach($array as $obj) {
  if($obj->cost > $max) {
    $max = $obj->cost;
    $max_obj = $obj;
  }
}

$max_obj现在是成本最高的对象。

答案 2 :(得分:0)

问题的两个简单解决方案(我更喜欢第二个):

function foreach_max($array) {
  $max = $array[0];

  foreach ($array as $row) {
    if ($row->cost > $max->cost) {
      $max = $row;
    }
  }

  return $max;
}

function reduce_max($array) {
  return array_reduce(array_slice($array, 1), function ($max, $row) {
    return $max->cost < $row->cost ? $row : $max;
  }, $array[0]);
}