简体   繁体   中英

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. Basically at the end I need array to be sorted with CRITICAL 1st with time stamp sorted then WARNING and then INFO so on..

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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