php根据其他数组的顺序重新排序数组

时间:2012-10-30 20:34:06

标签: php arrays sorting

鉴于此数组:

Array
(
[0] => Array
    (
        [title] => this is the newest post
        [ssm_featured_post_id] => 70
    )

[1] => Array
    (
        [title] => sdfsfsdf
        [ssm_featured_post_id] => 63
    )

[2] => Array
    (
        [title] => test
        [ssm_featured_post_id] => 49
    )

[3] => Array
    (
        [title] => Hello world!
        [ssm_featured_post_id] => 1
    )

ssm_featured_post_id值对应于第二个数组中数组项的值。 我想以与第二个数组中的项目相同的顺序排序第一个数组项目

Array
(
    [1] => 63
    [0] => 70
    [3] => 1
    [2] => 49
)

所以排序后的结果是

Array
(
[0] => Array
    (

        [title] => sdfsfsdf
        [ssm_featured_post_id] => 63
    )

[1] => Array
    (
        [title] => this is the newest post
        [ssm_featured_post_id] => 70
    )

[2] => Array
    (
        [title] => Hello world!
        [ssm_featured_post_id] => 1

    )

[3] => Array
    (
        [title] => test
        [ssm_featured_post_id] => 49
    )

)

2 个答案:

答案 0 :(得分:2)

更简单的方法是使用usort并编写一个使用第二个表来比较第一个表中的两个值的函数。

答案 1 :(得分:1)

您可能需要查看array_multisort,特别是给出的第三个示例。我们的想法是你根据多维数组的“列”创建数组,然后同时对它们进行排序,并将结果放回原始数组中。