PHP:如果值是数字,如何将数组项移动到第一位而不更改其键?

时间:2021-08-26 22:08:48

Here is my array:

这是我的阵列:

$arrayA = array(0 => "someString",
                1 => "otherString",
                2 => "2017",
                3 => "anotherString",
                4 => "2016"); 

My goal is to to find the first item that has a numeric value (which would be "2017") and place it first in the array, without changing its original key and keeping the others in the same order.

我的目标是找到第一个具有数值(即“2017”)的项目,并将其放在数组中,而不更改其原始密钥并使其他项保持相同的顺序。

So I want:

所以我想:

$arrayA = array(2 => "2017",
                0 => "someString",
                1 => "otherString",
                3 => "anotherString",
                4 => "2016"); 

I tried uasort() php function and it seems the way to do it, but I could not figure out how to build the comparison function to go with it.

我尝试了uasort()php函数,它似乎是这样做的,但我无法弄清楚如何构建比较函数来配合它。

PHP documentation shows an example:

PHP文档显示了一个示例:

function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

But, WHO is $a and WHO is $b?

但是,WHO是$ a,WHO是$ b?

Well, I tried

好吧,我试过了

    function my_sort($a,$b) {
        if ($a == $b ) {
            return 0;
        } 
        if (is_numeric($a) && !is_numeric($b)) {
            return -1;
            break;
        }
    }

But, of course, I am very far from my goal. Any help would be much appreciated.

但是,当然,我离目标很远。任何帮助将非常感激。

1 个解决方案

#1


3  

You don't need to sort per se. Once you find the element in question, you can simply push it onto the front of the array with the + operator:

您不需要排序本身。一旦找到有问题的元素,您只需使用+运算符将其推到数组的前面:

foreach ($arrayA as $k => $v) {
    if (is_numeric($v)) {
        $arrayA = [$k => $v] + $arrayA;
        break;
    }
}
print_r($arrayA);

Yields:

Array
(
    [2] => 2017
    [0] => someString
    [1] => otherString
    [3] => anotherString
    [4] => 2016
)

#1


3  

You don't need to sort per se. Once you find the element in question, you can simply push it onto the front of the array with the + operator:

您不需要排序本身。一旦找到有问题的元素,您只需使用+运算符将其推到数组的前面:

foreach ($arrayA as $k => $v) {
    if (is_numeric($v)) {
        $arrayA = [$k => $v] + $arrayA;
        break;
    }
}
print_r($arrayA);

Yields:

Array
(
    [2] => 2017
    [0] => someString
    [1] => otherString
    [3] => anotherString
    [4] => 2016
)