I have a array with much different combinations, now, i want to get the number/code that starts with _ at the begin of the array. I tried much things with usort, but not found the best fix.

Example array:

jhdjfhasjdfh234324
6524kl6j245-68tgh345345
ji43h593408ug8gfsspdkf
_23i490u2458djiofjgoskdgk
4534326jk36hj4j526hkj45t
43u25h6jih245ji3

And output:

_23i490u2458djiofjgoskdgk
jhdjfhasjdfh234324
6524kl6j245-68tgh345345
ji43h593408ug8gfsspdkf
4534326jk36hj4j526hkj45t
43u25h6jih245ji3

And, there can't be more codes that starts with _.

Thanks.

有帮助吗?

解决方案

function aux($a, $b) {
    if($a[0] == "_") return -1;
    else if($b[0] == "_") return 1;
    return ($a < $b) ? -1 : 1;
}

usort($data, "aux");

其他提示

Something like this should work

$f = false;
$data = array_filter($data, function($var) use(&$f) {
    if (substr($var, 0, 1) == "_") {
        $f = $var;
        return false;
    }

    return true;
});

if ($f) {
    array_unshift($data, $f);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top