简体   繁体   English

用两个子字符串对PHP字符串(行)数组进行排序

[英]Sort PHP array of string (line) with two substring

I wanted to sort php array based on CRITICAL , WARNING , INFO sub string and then CRITICAL , WARNING , INFO sub array should be sorted again with the time stamp value contains in each line of string in acsending order. 我想基于CRITICALWARNINGINFO子字符串对php数组进行排序,然后再对CRITICALWARNINGINFO子数组进行排序,并按升序将字符串的每一行中包含的时间戳记值进行排序。 Basically at the end I need array to be sorted with CRITICAL 1st with time stamp sorted then WARNING and then INFO so on.. 基本上,最后我需要使用CRITICAL 1st对数组进行排序,对时间戳进行排序,然后对WARNING进行排序,然后对INFO进行排序。

First, define a function that turns the urgency of a line into a number. 首先,定义一个函数,将线的紧迫性转化为数字。

function urgency($line)
{
    if (strpos($line, 'INFO') !== false) {
        return 1;
    } elseif (strpos($line, 'WARNING') !== false) {
        return 2;
    } elseif (strpos($line, 'CRITICAL') !== false) {
        return 3;
    }
    return 0;
}

Then, assuming each element of your array contains a line of the file, you need to apply a decorator to keep the sort stable; 然后,假设数组的每个元素都包含文件的一行,则需要应用装饰器以保持排序的稳定性。 see also my earlier answer on the subject: 另请参阅我先前关于该主题的答案

array_walk($array, function(&$element, $index) {
    $element = array($element, $index); // decorate
});

After applying the decorator, you sort the array; 应用装饰器后,对数组进行排序; I'm using a stable comparison helper: 我正在使用稳定的比较助手:

function stablecmp($fn)
{
    return function($a, $b) use ($fn) {
        if (($tmp = call_user_func($fn, $a[0], $b[0])) != 0) {
            return $tmp;
        } else {
            return $a[1] - $b[1];
        }
    };
}

usort($array, stablecmp(function($a, $b) {
    return urgency($b) - urgency($a);
}));

Finally, undecorate the array to produce the end result: 最后,取消装饰数组以产生最终结果:

array_walk($array, function(&$element) {
    $element = $element[0];
});

Getting CRITICAL on the sorted order 在已排序的订单上获得关键

function my_cmp($a, $b){
 $pieces_a = explode("CRITICAL", $a);
 $pieces_b = explode("CRITICAL", $b);

 if(!isset($pieces_a[1]) && isset($pieces_b[1])) {
    return 1;
 }
 elseif(!isset($pieces_b[1]) && isset($pieces_a[1])) {
    return -1;
 }
 elseif(!isset($pieces_a[1]) && !isset($pieces_b[1])) {
    return 0;
 }
 return strcasecmp($pieces_a[1], $pieces_b[1]);
}
usort($arr, "my_cmp");

But this can only sort if the each line has non spaces I mean single word,. 但这只能在每行都有非空格的情况下进行排序,我的意思是单个单词。

Any other solution curious to know? 还有其他想知道的解决方案吗?

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

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