0

Utilising the power of uksort (although happy to be directed elsewhere if necessary), I'm looking at implementing a custom sort routine to sort, in ascending order, an array based on its key.

The problem I'm having is the key is a string, but I'd like to treat the key as an int (in two parts). My array is as follows:

[20-2 => object, 20-1 => object, 4-1 => object, 3-1 => object]

What I would like to do is order primarily by the int value of the first half of the key, then the second half (where there are multiple entries that share the first half). For instance, I would like to order to the following:

[3-1 => object, 4-1 => object, 20-1 => object, 20-2 => object]

Thanks

Tried ksort, but because my keys are strings it pretty much did nothing

Edit: I do NOT have access to the creation of the array in order to change the keys into something more easily sortable. I am using PHP7

nice_dev
  • 17,053
  • 2
  • 21
  • 35
Hogan
  • 1
  • 2
  • 1
    Please share more details, like the source array in PHP code, the target array, and your attempts to resolve the problem – Nico Haase Apr 24 '23 at 12:28
  • `uksort` should work just fine with a correct implementation. See https://3v4l.org/T0C5U – nice_dev Apr 24 '23 at 12:34
  • @nice_dev That looks suspiciously like an answer. Any reason not to post it as one? – IMSoP Apr 24 '23 at 12:35
  • 1
    @nice_dev Your solution works perfectly. I think my issue here is that I need to go away and get a better understanding of how to implement a custom sort correctly, in all situations, rather than relying on PHP to do the heavy lifting – Hogan Apr 24 '23 at 12:40
  • @IMSoP I am under the impression that there would surely be a dupe for this. Hence, not taking any risks since mods would later on close this page with a dupe post. – nice_dev Apr 24 '23 at 12:44
  • @JoeHogan Makes sense. PHP can do the heavy lifting for you, but it's better to make and store the data in the right format to avoid redundant manipulations in the future. – nice_dev Apr 24 '23 at 12:45
  • 1
    @nice_dev Answering in a comment is the worst of both worlds, from the site's point of view: it can't be upvoted or accepted as an Answer (nor edited or downvoted, if necessary); but the person asking the question gets what they need, so doesn't need to engage with the site any more, and we're left with a stub. – IMSoP Apr 24 '23 at 13:59
  • 2
    As for duplicates, we have a general reference on sorting in PHP, so if it's just a case of needing to understand the principles, rather than fixing a problem with an existing implementation, that would be the place to go. – IMSoP Apr 24 '23 at 14:01
  • Thanks all for your help and clarification of site best practices – Hogan Apr 24 '23 at 14:40
  • @IMSoP Makes sense to me now. I will abide by it. – nice_dev Apr 24 '23 at 14:41

0 Answers0