简体   繁体   English

查找下一个最高的阵列键

[英]Find the next highest array key

Is there a one liner for finding an integer key equal to or greater than a given index? 是否找到一个等于或大于给定索引的整数键的衬里? To make things clear, here's an example of an array I'm working with. 为了清楚起见,这是我正在使用的数组的示例。

array( 4294967295 => 'LONGTEXT'
     , 16777215   => 'MEDIUMTEXT'
     , 65535      => 'TEXT'
     , 255        => 'TINYTEXT' );

As some of you may recognize, these are MySQL column definition types. 你们中有些人可能认识到,这些是MySQL列定义类型。 Let's say I'm given an integer 500 , how can I quickly/compactly find the next key of 65535 which maps to 'TEXT' ? 假设我得到一个整数500 ,如何快速/紧凑地找到映射到'TEXT'的下一个键65535

Currently I iterate the array using foreach (hence highest values first) and track the last key. 目前,我使用foreach迭代数组(因此首先获得foreach )并跟踪最后一个键。 But, due to the number of arrays and data types I'm dealing with, the function has become bloated. 但是,由于我要处理的数组和数据类型数量众多,该功能变得肿了。

This is compact and should work: 这是紧凑的,应该可以工作:

$sizes = array_filter(array_keys($array), function($element) use ($size) { return $element >= $size; });
$array[array_pop($sizes)];

This will emit an undefined index error if no type large enough exists in $array . 如果$array没有足够大的类型,则将发出未定义的索引错误。 I really wouldn't consider it optimal - the best solution is rarely the shortest possible. 我真的不会认为它是最佳的-最佳解决方案很少是最短的。

Consider using something like this, which is more robust: 考虑使用这样的方法,它更可靠:

function getType(array $types, $desiredSize) { // $types should be sorted by key asc
    foreach($array as $length => $type) {
        if($length >= $desiredSize) {
            return $type;
        }
    }

    return null; // no type large enough
}

$types = array(
        4294967295 => 'LONGTEXT',
        16777215 => 'MEDIUMTEXT',
        65535 => 'TEXT',
        255 => 'TINYTEXT');
ksort($types); // or hardcode it in asc order

echo getType($types, 500); // TEXT

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM