Php 查找数组中键的最大值

Php 查找数组中键的最大值,php,arrays,Php,Arrays,我有一个数组 [DoctorEducation] => Array ( [0] => Array ( [id] => 24 [user_id] => 91 [degree_type_id] => 1

我有一个数组

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

            )
现在我想找出哪个索引,即
0
1
等等,具有
度类型id
的最大值。例如,在当前数组中,索引
1
的最大值为
degree\u type\u 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)));

也许有一种更快的方法可以做到这一点,但我的解决方案是:

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

试着这样做:

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

这为您提供了具有最高级别\u type\u id的键的索引和值,非常简单,有几个功能:

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

如果出现多个最大值,则您将获得第一个值。

如果您是从数据库中获取此值,为什么不使用数据库查询来获取它呢you@MarkBaker:是的,我从DB那里得到这个。检查我更新的问题以进行查询。
$maxId=array_search(array_列($myArray['DoctorEducation'],'degree_type_id'),max(array_列($myArray['DoctorEducation'],'degree_type_id')你在使用框架吗,orm?我在使用框架
cakephp
。谢谢。成功了。我不知道我怎么会错过这种方法。我觉得困了D;)