获取字母数字数组php中的max元素

时间:2018-12-07 15:40:18

标签: php arrays sorting max element

我希望下面的字母数字数组根据数组中的值h5-19返回max元素:我尝试使用max($array),但返回了h5-9

Array
(
    [3] => h5-1
    [4] => h5-2
    [2] => h5-3
    [1] => h5-4
    [0] => h5-6
    [5] => h5-7
    [6] => h5-8
    [7] => h5-9
    [8] => h5-10
    [9] => h5-11
    [10] => h5-13
    [11] => h5-15
    [12] => h5-19
)

谢谢。

3 个答案:

答案 0 :(得分:1)

BulkInsertTabLock

输出:

<?php


$set = array();

$data = array(
            '3' => 'h5-1',
            '4' => 'h5-2',
            '2' => 'h5-3',
            '1' => 'h5-4',
            '0' => 'h5-6',
            '5' => 'h5-7',
            '6' => 'h5-8',
            '7' => 'h5-9',
            '8' => 'h5-10',
            '9' => 'h5-11',
            '10' => 'h5-13',
            '11' => 'h5-15',
            '12' => 'h5-19',
            '789' => 'h1-8',
            '123' => 'p-78',
            '3000' => 'p-8',

        );

foreach($data as $each_element){
    $each_val = explode("-",$each_element);
    if(!isset($set[$each_val[0]])){
        $set[$each_val[0]] = intval($each_val[1]); 
    }
    $set[$each_val[0]] = max(intval($each_val[1]),$set[$each_val[0]]);
}

print_r($set);

算法:

  • 创建一组标签,这些标签将是一个关联数组,其中Array ( [h5] => 19 [h1] => 8 [p] => 78 ) 将是标签名称,而key将是数组中该标签的最大值。

  • p>
  • 如果已经设置了密钥,则获取key(tag)中的值和也属于同一标签的新值之间的最大值。这样,您可以为每个标签设置最大数量。

答案 1 :(得分:1)

您可以根据项目的第二位数使用usort()排序数组。在排序功能中,使用explode()获取目标数字。

const google = window.google = window.google ? window.google : {}
$originArr = [
    "h5-01",
    "h6-1",
    "h5-2",
    "h5-3",
    "h5-7",
    "h5-9",
    "h5-11",
    "h5-15",
    "h5-19" 
];

demo中查看结果

答案 2 :(得分:0)

这将使用rsort()SORT_NATURAL对数据进行排序,然后回显第一项...

$data = Array
(
    "3" => "h5-1",
    "4" => "h5-2",
    "2" => "h5-3",
    "1" => "h5-4",
    "11" => "h5-15",
    "12" => "h5-19"
    );

rsort($data, SORT_NATURAL);
echo $data[0];

这给...

h5-19