paul
paul

Reputation: 572

php reorder array based on order of other array

Given this array:

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
    )

)

The ssm_featured_post_id value corresponds to the value of the array items in the second array. I want to order the first array items in the same order as the items in the second array

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

so the result after sorting would be

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
    )

)

Upvotes: 3

Views: 121

Answers (2)

Korri
Korri

Reputation: 657

The simpler way would be to use usort and write a function that uses the second table to compare two values from first table.

Upvotes: 2

Patrick White
Patrick White

Reputation: 681

You may want to check out array_multisort, particularly the third example given. The idea is that you create arrays based on the "columns" of the multidimensional array, then sort them simultaneously, and put the result back in the original array.

Upvotes: 1

Related Questions