0

I have this unconventional need to sort an array by an order defined in a different array. Let me elaborate with a simplified example:

$myArr = ['Dog', 'Cat', 'Giraffe', 'Shark'];
$orderArr = ['Giraffe', 'Dog', 'Shark', 'Cat'];

$myArr needs to be modified to have the order of $orderArr. The task is so nonsensical as it seems. In reality $myArr is an array of object. $orderArr provides only a template for sorting - it holds only one propery of the objects of $myArr.

Perhaps one way would be to use array_walk:

array_walk($myArr, function($v, $k) {       
...
}, $orderArr);

I have hard times soliving this puzzle.

It'd be great to see your take on it!

Important

This question is by no way similar to the one presented in "possible duplicate" comment and should not be marked as duplicate. In the one qoted in the comment, there is a question about how an array can be sorted by one of its values, and not be an external 'template array'.

luqo33
  • 8,001
  • 16
  • 54
  • 107
  • Why can't you just create a new, sorted array with the same data? Why does it have to be edited directly? – Mike Purcell Sep 29 '15 at 19:09
  • Definitely a duplicate, but perhaps this is more specific for your case: http://stackoverflow.com/questions/348410/sort-an-array-by-keys-based-on-another-array?rq=1. If not, check the right-hand bar there. – jeroen Sep 29 '15 at 19:09
  • @MikePurcell I have no control over the order items are pushed to $myArr at the time of its creation. I can only edit a ready array. – luqo33 Sep 29 '15 at 19:15
  • Still doesn't make sense, you are "black boxing" the manipulation of the $myArr, so that it is sorted, so the calling code is expecting a sorted array, what difference does it make if it's the original or a new array with the same elements, only sorted? The reason why I am asking is b/c it would be easier to step through $myArr, and match with the template array, then generate a new array, removing elements of $myArr until it is empty. Then return the new array. – Mike Purcell Sep 29 '15 at 19:18
  • @MikePurcell You're right, a new array can be returned. This constraint should not be in the question. – luqo33 Sep 29 '15 at 19:21
  • Pretty much gave you the answer, you should be good to go. – Mike Purcell Sep 29 '15 at 19:24
  • I just flagged this question for *reopening*. This question is clearly NOT a duplicate of http://stackoverflow.com/questions/2699086/sort-multi-dimensional-array-by-value Everybody please be more careful when flagging. – tacone Sep 29 '15 at 19:51
  • @luqo33: not sure how efficent this is, but you could try this approach as a starting point http://pastebin.com/dPAfdZbA – tacone Sep 29 '15 at 20:13

0 Answers0