Q . sort an array with another array which has sorted keys

Dev Singh. asked, Jun 09 ' 2017

How to sort an 1st array with 2nd array which has sorted keys in 2nd array without using any loop.

1st Array.

$chunk = array(
                [0] => Array
                    (
                        [id] => 212
                        [order] => 1
                        [title] => fdfdfdfdf
                    )

                [1] => Array
                    (
                        [id] => 5
                        [order] => 2
                        [title] => 
                    )

                [2] => Array
                    (
                        [id] => 781
                        [order] => 3
                        [title] => 
                    )
            )

2nd array with sorted keys of 1st array.

$sort = array
    (
        [2] => 2
        [0] => 0
        [1] => 1
    )

 

  • PHP
  • arrays
  • sorting

1 Answers

You could use array_map for that:

$arr = array_map(function($val) use($chunk){
    return $chunk[$val];
}, $sort);

This is the output:

Array
(
    [2] => Array
        (
            [id] => 781
            [order] => 3
            [title] => 
        )

    [0] => Array
        (
            [id] => 212
            [order] => 1
            [title] => fdfdfdfdf
        )

    [1] => Array
        (
            [id] => 5
            [order] => 2
            [title] => 
        )

)

Now, if you want the keys to be 0,1,2..., you can use array_values, after mapping:

$arr = array_values($arr);

And the output:

Array
(
    [0] => Array
        (
            [id] => 781
            [order] => 3
            [title] => 
        )

    [1] => Array
        (
            [id] => 212
            [order] => 1
            [title] => fdfdfdfdf
        )

    [2] => Array
        (
            [id] => 5
            [order] => 2
            [title] => 
        )

)

 

Leave a Ansewer