-4

So I have the following data array:

array (size=10)
  0 => int 5
  1 => string '5B1' (length=7)
  2 => int 4
  3 => string '4B1' (length=7)
  4 => int 3
  5 => string '3B1' (length=7)
  6 => int 2
  7 => string '2B1' (length=7)
  8 => int 1
  9 => string '1B1' (length=7)

What I want to do is sort it to this:

array (size=10)
  0 => string 5B1
  1 => int '5' (length=7)
  2 => string 4B1
  3 => int '4' (length=7)
  4 => string 3B1
  5 => int '3' (length=7)
  6 => string 2B1
  7 => int '2' (length=7)
  8 => string 1B1
  9 => int '1' (length=7)

The hierarchy of the numbers never change although there is an additional level as seen here:

7 -> 6b2 -> 6b1 -> 6 -> 5b2 -> 5b1 -> 5 4b2 -> 4b1 -> 4 -> 3b2 -> 3b1 -> 3 -> 2b2 -> 2b1 -> 2 -> 1b2 -> 1b1 -> 1 -> b2 -> b1

I am wondering what is the best way to sort this in PHP?

On the one hand I am thinking of looping through the static hierarchy array from top to bottom and using this to order the dynamic array.

Any other suggestions?

HappyCoder
  • 5,285
  • 4
  • 36
  • 67
  • 3
    Have you considered using PHP's [rsort()](http://www.php.net/manual/en/function.rsort.php) function with the `SORT_NATURAL` flag? – Mark Baker Jan 07 '16 at 19:14
  • have you tried testing yourself? read manual about array related methods? – Marcin Orlowski Jan 07 '16 at 19:14
  • http://php.net/manual/en/array.sorting.php Lists the array sorting functions – developerwjk Jan 07 '16 at 19:14
  • @MarkBaker Yes, I have been reading the manual quite extensively on this one. It seems like a simple solution, but not as simple as you may at first think. rsort gets the order wrong (5 -> 5b1 -> 4b1 -> 4 as apposed to 5b1 -> 5 -> 4b1-> 4) . I don't believe there is a pre-built function that can sort this, hence my question about using a compare array. – HappyCoder Jan 07 '16 at 19:24
  • @MarcinOrlowski - lots of testing, nothing pre-built appears to suit my needs hence my question. I am probably going to compare to a pre-defined array with the order in it. Before I did that, wanted to see what others suggest. – HappyCoder Jan 07 '16 at 19:28
  • @MarkBaker - ahh thats what I need, the blasted manual I am using does not list "SORT_NATURAL"... that has saved me some time! – HappyCoder Jan 07 '16 at 19:34
  • 2
    Possible duplicate of [How can I sort arrays and data in PHP?](http://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php) – user3942918 Jan 07 '16 at 19:51

1 Answers1

0

The answer to this was quite simple, Mark Baker put me on the right track.

I originally used a convoluted mix between rsort, krsort and array_flip to get an almost working solution.

Using rsort with the SORT_NATURAL flag did the trick.

HappyCoder
  • 5,285
  • 4
  • 36
  • 67