【问题标题】:How to find min value and its associative key in an array [duplicate]如何在数组中找到最小值及其关联键[重复]
【发布时间】:2018-05-16 05:24:10
【问题描述】:

我正在尝试获取具有最小值的数组的键和值。 这是我的代码。 我有空值变量 我想要不为空的值,并且从值中,我需要一个键和值 min 从数组或任何其他模式(如果可能)。

 <?php
      $serial_sale_price    ='2';
        $promo_sale_price   ='';
        $inv_sale_price     ='300.00';
        $price_search_seq = 'B';
        //validate for 0 values
        if($serial_sale_price!='' && $serial_sale_price==0)
        {
            $serial_sale_price='0.00';
        }
        if($promo_sale_price!='' && $promo_sale_price==0)
        {
            $promo_sale_price='0.00';
        }
        if($inv_sale_price!='' && $inv_sale_price==0)
        {
            $inv_sale_price='0.00';
        }


        $remove_empty = array('S'=>$serial_sale_price,
                               'P'=>$promo_sale_price, 
                               'I'=>$inv_sale_price);
        $find_min = array_filter($remove_empty); // Array which required in 
        echo "<pre>";
        print_r($find_min);
        $sale_price =  min($find_min);//Minimum Price for the array 
        $price_rule = '';//here i want to get the key which have min value

        echo "sales price:$sale_price,price_rule:$price_rule";

如何一次获取最小值的key和最小值的key。 我对我的例子的期望。 如果最小值为 serial_sales_price,则键为 'S',值为 2

【问题讨论】:

  • 请学习做基础研究——在谷歌中输入“php array get min and key”就可以找到这个了。

标签: php arrays


【解决方案1】:
// Sample by PHP Method 

$var = array_keys($remove_empty , min($remove_empty ));
//$var[0] for letest key have minimum value.    

//This function returns the key for the minimum value. 

function getMinKey( $array )
{
    $min = 0;
    $key = '';
    foreach( $array as $k => $v )
    {
        $min = min($array);
    }
    foreach( $array as $k => $v )
    {

        if($min == $v)
        {
            $key = $k;
        }


    }
    return $key;
}

  echo getMinKey($remove_empty); // for min value key; 

【讨论】:

    猜你喜欢
    • 2010-12-07
    • 2018-12-29
    • 2011-03-04
    • 2016-06-07
    • 1970-01-01
    • 2021-02-19
    • 2012-11-03
    • 1970-01-01
    • 2012-10-11
    相关资源
    最近更新 更多