1

So I have an array such as this one:

Array
(
    [-1] => Array
        (
            [3] => 3
            [1] => 1
            [6] => 6
            [7] => 7
            [5] => 5
        )
)

It also contains some other keys that should not be modified.

I'd like to the numbers which are in a second array to come first (in the order of that second array), and then will be the numbers that don't exist in the second array, if any.

So for that matter, the second array would be:

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

And the final array should be as follows (please remember, there are some more keys inside of that array that should stay as they are):

Array
(
    [-1] => Array
        (
            [6] => 6
            [5] => 5
            [3] => 3
            [1] => 1
            [7] => 7
        )
)

Any ideas how that can be done?

Thanks!

5
  • 2
    This doesn't look like an array. Nor like a sorting... Commented Mar 25, 2011 at 22:14
  • Array, yes. PHP arrays are actually ordered maps. But i don't see the logic behind the "sorting". I have a feeling the word is being misused here. Commented Mar 25, 2011 at 22:20
  • Well, in summary, I need the numbers from the second array to be first (by order), then the numbers that don't exist in the second array, if any. Commented Mar 25, 2011 at 22:24
  • I think that you should have used the term permutation and not sorting. Commented Mar 25, 2011 at 22:46
  • You want to permute the first array according to the second (that defines the partial permutation) and push what's left of the first array to the end. Commented Mar 25, 2011 at 22:51

2 Answers 2

1

It's not and shouldn't be termed as sorting but may be this code snippet may help you do what you want to:

         $a1 = Array ( [-1] => Array ( [3] => 3 [1] => 1 [6] => 6 [7] => 7 [5] => 5 ) );
            $a2 = Array ( [0] => 6 [1] => 5 [2] => 3 );
            $sorted = getSortedArray($a1[-1] , $array2);
                function getSortedArray($array1 , $array2){
                 $temp = Array();
                 $count = 0;
                 $totalKeys = sizeof($array2);
                 for($i=0;$i<sizeof($array2);$i++){


 $temp[i] = $array1[$array2[i]];      
unset($array1[$array2[i]]);
    }
                 while($count!=sizeof($array1))
                          $temp[$totalKeys++] = $array1[$count++];                      
        return $temp;   



        }
Sign up to request clarification or add additional context in comments.

Comments

0

I believe the function you're looking for is called array_multisort().

array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.