按一列对二维数组中的行进行排序,同时保留原始的列关系

发布于 2024-10-20 14:10:43 字数 778 浏览 2 评论 0原文

我的数组如下所示:

Array
(
[0] => Array
    (
        [0] => 1
        [1] => 6
        [2] => 4
        [3] => 5
    )

[1] => Array
    (
        [0] => 272.05
        [1] => 63.54
        [2] => 544.79
        [3] => 190.62
    )

[2] => Array
    (
        [0] => 2011-03-06 14:08:19
        [1] => 2011-03-06 14:29:04
        [2] => 2011-03-06 14:28:39
        [3] => 2011-03-06 14:29:28
    )

)

我想按 $myArray[1] 排序。我有这个 usort 函数:

function sortAmount($a, $b) { 
    return strnatcmp($a[1], $b[1]); 
}

它是这样调用的:

usort($myArray, "sortAmount"); 

但是,调用 usort 后数组不会改变。我希望 $myArray[1] 中的数字按升序排序,并且 $myArray[0] 和 $myArray[2] 中的相应索引随之更改。

My array looks like this:

Array
(
[0] => Array
    (
        [0] => 1
        [1] => 6
        [2] => 4
        [3] => 5
    )

[1] => Array
    (
        [0] => 272.05
        [1] => 63.54
        [2] => 544.79
        [3] => 190.62
    )

[2] => Array
    (
        [0] => 2011-03-06 14:08:19
        [1] => 2011-03-06 14:29:04
        [2] => 2011-03-06 14:28:39
        [3] => 2011-03-06 14:29:28
    )

)

I want to sort by $myArray[1]. I have this usort function:

function sortAmount($a, $b) { 
    return strnatcmp($a[1], $b[1]); 
}

It is called like this:

usort($myArray, "sortAmount"); 

However, the array does not change after calling usort. I want the numbers in $myArray[1] to be sorted in ascending order, and for the corresponding indexes in $myArray[0] and $myArray[2] to change with it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

折戟 2024-10-27 14:10:43

我想你想要 array_multisort:

array_multisort($a[1], $a[0], $a[2]);

给出

Array
(
    [0] => Array
        (
            [0] => 6
            [1] => 5
            [2] => 1
            [3] => 4
        )

    [1] => Array
        (
            [0] => 63.54
            [1] => 190.62
            [2] => 272.05
            [3] => 544.79
        )

    [2] => Array
        (
            [0] => 2011-03-06 14:29:04
            [1] => 2011-03-06 14:29:28
            [2] => 2011-03-06 14:08:19
            [3] => 2011-03-06 14:28:39
        )

)

Apart由此看来,为什么要使用 strcmp 来比较数字

I think you want array_multisort:

array_multisort($a[1], $a[0], $a[2]);

gives

Array
(
    [0] => Array
        (
            [0] => 6
            [1] => 5
            [2] => 1
            [3] => 4
        )

    [1] => Array
        (
            [0] => 63.54
            [1] => 190.62
            [2] => 272.05
            [3] => 544.79
        )

    [2] => Array
        (
            [0] => 2011-03-06 14:29:04
            [1] => 2011-03-06 14:29:28
            [2] => 2011-03-06 14:08:19
            [3] => 2011-03-06 14:28:39
        )

)

Apart from that, why do you use strcmp to compare numbers?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文