How To Get ALL Minimum Value Within Multidimensional Array?

时间:2016-02-03 04:15:32

标签: php arrays multidimensional-array

I have this code :

<?php

$result = array ( array ("split" => "2", "combo" => "4,3"),
                  array ("split" => "2", "combo" => "6,1"),
                  array ("split" => "3", "combo" => "2,1"),
                  array ("split" => "4", "combo" => "1,1,1,1"));

$min_x = min ( array_column( $result, 'split' ) );

print_r($min_x);
?>

this will give me 2 as result and I need to create some function to get the combo value of 2, how to get both array value of 2 using native PHP function (is there any?) like this :

array ( array ("split" => "2", "combo" => "4,3"),
        array ("split" => "2", "combo" => "6,1"));

4 个答案:

答案 0 :(得分:4)

您可以使用minarray_column获取最低数量,最后只需使用array_filter

$result = array ( array ("split" => "2", "combo" => "4,3"),
                  array ("split" => "2", "combo" => "6,1"),
                  array ("split" => "3", "combo" => "2,1"),
                  array ("split" => "4", "combo" => "1,1,1,1"));

$min = min(array_column($result,'split'));
$res = array_filter($result,function($v)use($min){ 
    return $v['split'] == $min;
});

print_r($res);

输出:

Array
(
    [0] => Array
        (
            [split] => 2
            [combo] => 4,3
        )

    [1] => Array
        (
            [split] => 2
            [combo] => 6,1
        )

)
  

注意:使用PHP版本&gt; = 5.5.0

答案 1 :(得分:1)

$arr_min = array();
$arr_min["split"] = min ( array_column( $result, 'split' ) );
$arr_min["combo"] = min ( array_column( $result, 'combo' ) );

现在你有两个键的最小值数组。这只是一个抽象的想法。你也可以让它变得动态。

答案 2 :(得分:1)

你可以试试这个,

<?php
$result = array ( array ("split" => "7", "combo" => "4,3"),
              array ("split" => "2", "combo" => "6,1"),
              array ("split" => "9", "combo" => "2,1"),
              array ("split" => "8", "combo" => "1,1,1,1"));
array_multisort($result);
print_r($result[0]['combo']);
?>

答案 3 :(得分:1)

你可以这样做:

<?php

$result = array ( array ("split" => "2", "combo" => "4,3"),
                  array ("split" => "2", "combo" => "6,1"),
                  array ("split" => "3", "combo" => "2,1"),
                  array ("split" => "4", "combo" => "1,1,1,1"));

$min_x = min ( array_column( $result, 'split' ) );

$new_result = array();
foreach($result as $val){
    if($val["split"] == $min_x)
    $new_result[] = $val;
}
echo "<pre>";
print_r($new_result);

?>

输出:

Array
(
    [0] => Array
        (
            [split] => 2
            [combo] => 4,3
        )

    [1] => Array
        (
            [split] => 2
            [combo] => 6,1
        )

)