找到数组中键的最大值

时间:2016-01-18 19:09:04

标签: php arrays

我有一个数组

 [DoctorEducation] => Array
            (
                [0] => Array
                    (
                        [id] => 24
                        [user_id] => 91
                        [degree_type_id] => 1
                        [college_hospital] => sms
                        [diploma_name] => 
                        [specialization_id] => 0
                        [start_date] => 02/2009
                        [end_date] => 03/2012
                        [year_passing] => 0000
                        [created] => 2015-10-09 13:14:23
                        [updated] => 2015-10-09 13:16:18
                    )

                [1] => Array
                    (
                        [id] => 26
                        [user_id] => 91
                        [degree_type_id] => 5
                        [college_hospital] => sms
                        [diploma_name] => 
                        [specialization_id] => 48
                        [start_date] => 03/2012
                        [end_date] => 05/2014
                        [year_passing] => 0000
                        [created] => 2015-10-09 13:16:18
                        [updated] => 2015-10-09 13:16:18
                    )

            )

现在我想找出哪个索引,01等具有最大值degree_type_id。例如,在当前数组中,索引1的最大值为degree_type_id,即5。

我从DB那里得到这个。这是查询

 $fields = array(
        'User.id',
        'User.first_name',
        'User.last_name',
        'User.gender',
        'User.dob',
        'User.image',
        'Specialization.name',
        'User.age'
    );
    $getSpecialist = $this->User->find('all', array('fields' => $fields), array('conditions' => array('User.role_id' => 3, 'User.status' => 1)));

3 个答案:

答案 0 :(得分:1)

尝试这样的事情:

    $max_index = null;
    $max_value = 0;
    foreach($DoctorEducation as $key => $array){
      if($array['degree_type_id'] > $max_value){
        $max_value = $array['degree_type_id'];
        $max_index = $key;
      }
    }
print_r($DoctorEducation[$max_index]);

这为您提供了具有最高 degree_type_id

的键的索引和值

答案 1 :(得分:0)

可能有更快的方法来做到这一点,但这是我的解决方案:

$to_compare = array(); 
foreach($DoctorEducation as $idx => $arr){
    $to_compare[$idx] = $arr['degree_type_id'];
}

$max = $to_compare[array_search(max($to_compare), $to_compare)];

答案 2 :(得分:0)

使用多种功能非常简单:

$key = array_search(max(array_column($array['DoctorEducation'], 'degree_type_id')),
                    $array['DoctorEducation']);
  • 将适当的列提取到数组
  • 查找该列数组中的最大值
  • 在该列数组中搜索最大值,该值返回键

如果出现多个最大值,那么您将得到第一个。