0

I have the following array that indicates the order on how to sort the DATA array:

 $PARENT_ID_ORDER = array(1, 3, 2); 

Here's the DATA array, which contains PARENT_ID key, I want to sort by PARENT_ID key using my PARENT_ID_ORDER:

 $DATA = array (
     array (
        'PARENT_ID' => 2;
     ),
     array (
        'PARENT_ID' => 2;
     ),
     array (
        'PARENT_ID' => 1;
     ),
     array (
        'PARENT_ID' => 3;
     ),
     array (
        'PARENT_ID' => 1;
     ),
     array (
        'PARENT_ID' => 2;
     ),
     array (
        'PARENT_ID' => 2;
     )
 );

The expected output:

 array(
        [0] => Element Object
            (
                [PARENT_ID] => 1,
            ),
        [1] => Element Object
            (
                [PARENT_ID] => 1,
            ),
        [2] => Element Object
            (
                [PARENT_ID] => 3,
            ),
        [3] => Element Object
            (
                [PARENT_ID] => 2,
            ),
        [4] => Element Object
            (
                [PARENT_ID] => 2,
            ),
        [5] => Element Object
            (
                [PARENT_ID] => 2,
            ),
        [6] => Element Object
            (
                [PARENT_ID] => 2,
            )
 );

How can I provide my order array to sort function so it gets sorted this way? Thanks!

Kristian
  • 1,348
  • 4
  • 16
  • 39
  • Please see this duplicate: http://stackoverflow.com/questions/11145393/sorting-a-php-array-of-arrays-by-custom-order – GBD Nov 09 '14 at 14:46

1 Answers1

1

I think you're looking for this http://php.net/manual/en/function.usort.php. You can use this along with binary search or inbuilt array_search if array is small

VigneshM
  • 157
  • 1
  • 9
  • 1
    Or as an alternative to binary search / array_search, array_flip the $PARENT_ID_ORDER array and then index into it and compare the values. – Laird Nov 09 '14 at 14:49