如何在php中获取数组内最大值的数组

时间:2014-11-25 19:22:56

标签: php arrays

我有一个看起来像这样的数组: -     


    $my_array = array();
    $my_array[] = array("is_match" => false, "number_of_matches" => 0);
    $my_array[] = array("is_match" => true, "number_of_matches" => 2, "id" => 1);
    $my_array[] = array("is_match" => false, "number_of_matches" => 5, "id" => 1);
    $my_array[] = array("is_match" => false, "number_of_matches" => 3, "id" => 1);
    $my_array[] = array("is_match" => false, "number_of_matches" => 1, "id" => 1);
    

现在我想获得具有最大匹配数的数组,即number_of_matches。就像在这个例子中我想要得到数组     


    array("is_match" => false, "number_of_matches" => 5, "id" => 1);
    

我知道max()函数,但它返回数组中的最大值,但我想返回包含number_of_mataches中最大值的数组

3 个答案:

答案 0 :(得分:1)

如果你真的只想要最大number_of_matches元素,那么我认为uasort有点矫枉过正,可能需要更长时间才能执行(但差异可能是微不足道的。)

$max = false;
foreach ($my_array as $a) {
    if (!$max || $max['number_of_matches'] < $a['number_of_matches']) {
        $max = $a;
    }
}

唯一的限制是它将返回第一个最大值而不是其他最大值。绕过这个限制(这比uasort更长,但可能仍然比排序更快):

$max = false;
foreach ($my_array as $a) {
    if (!$max || $max['number_of_matches'] < $a['number_of_matches']) {
        $max = $a;
        $max_array = array();
        $max_array[] = $a;
    } else if ($max['number_of_matches'] == $a['number_of_matches']) {
        $max_array[] = $a;
    }
}

答案 1 :(得分:1)

您可以使用uasort

function cmp($a, $b) {
    if ($a['number_of_matches'] == $b['number_of_matches']) {
        return 0;
    }
    return ($a['number_of_matches'] < $b['number_of_matches']) ? 1 : -1;
}

uasort($my_array, 'cmp');

echo $my_array[0]['number_of_matches'];

$my_array[0]将保留具有最高number_of_matches

的数组

答案 2 :(得分:1)

您可以通过以下方式实现此目的:

usort($my_array, function($a, $b) {
    return $b['number_of_matches'] - $a['number_of_matches'];
});