3

我有这个数组

$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) 

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

4

5 回答 5

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)";

?>
于 2013-06-26T06:46:04.267 回答
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);
于 2013-06-26T06:38:37.047 回答
1

您只能使用asort和获取第一个键和值。

 asort($data);

foreach($data as $key=>$val) {
    echo $key." ".$val; break;
}
于 2013-06-26T06:44:12.853 回答
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 );
?>
于 2013-06-26T06:40:41.747 回答
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)
于 2013-06-26T06:36:27.453 回答