多维数组中的最小值

时间:2013-06-26 06:31:30

标签: php multidimensional-array

我有这个数组

$data['key'] = array(11,5,7);
$data['value'] = array(78,54,96);

我根据价值对其进行了分类。所以我现在 -

$ data [' key'] =(5,11,7); $ data [' value'] =(54,78,96);

如何获得第一组键值对,即具有最小值的键值对。

我希望o / p为 -

(5,54) 

有人可以解释一下如何做到这一点吗?

5 个答案:

答案 0 :(得分:1)

简单:

foreach($data['key'] as $val)
{
   if(isset($min_val)
   {
      if($val<$min_val)
      {
         $min_val=$val;
      }
   }
   else
   {
         $min_val=$val;
   }


}

您还可以使用min()功能。 例如:

   $output = array();
   $output []= min(array(11,5,7)); //will output 5
   $output[]=  min(array(78,54,96)); //will output 54
   print_r($output); //out put will be (5,54)

答案 1 :(得分:1)

$data['key'] = array(11,5,7);
$data['value'] = array(78,54,96);
$min = min($data['value']);
$key = array_search($min,$data['value']);
$result = array($data['key'][$key],$min);

答案 2 :(得分:1)

你是说,这是什么意思?我真的不知道你想要实现的目标

<?php
  // minimum value from both key and value
  $temp = array_map( "min", $data );
  print_r( $temp );

  // or if you only want to find the key of minimum value
  $value  = min( $data['value'] );
  $key    = $data['key'][array_search( $value, $data['value'] )];
  $temp   = array( $key, $value );
  print_r( $temp );

  // or if you want the first key value pairs
  reset( $data );
  $temp   = array( current( $data['key'] ), current( $data['value'] ) );
  print_r( $temp );
?>

答案 3 :(得分:1)

您可以使用asort并仅获取第一个键和值。

 asort($data);

foreach($data as $key=>$val) {
    echo $key." ".$val; break;
}

答案 4 :(得分:1)

以下算法将解决您想要在O(n)时间内实现的目标,

<?php
$data['key']    = array( 11, 5, 7 );
$data['value']  = array( 78, 54, 96 );

$min_value=$data["value"][0]; //temporarily set first element as current minimum
$min_index=$data["key"][0];

foreach($data["value"] as $key => $val){
    if($val <= $min_value){
        //we have a new minimum value 
        $min_value = $val;
        $min_index = $data['key'][$key];
    }
}

echo "($min_index => $min_value)";

?>