0

您好以下是数组的输出:

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
        )

)

谢谢。

4

3 回答 3

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');
于 2013-08-07T10:33:36.207 回答
1
$max = -999;
$max_obj = NULL;

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

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

于 2013-08-07T10:34:09.617 回答
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]);
}
于 2013-08-07T10:56:25.643 回答