I want to sort an array in a complicated way and am not sure how to go about it. Here is a rough idea of the data I'm working with:
[
{ target: random.text.cpu-pct-0, otherData[...] },
{ target: random.text.cpu-pct-1, otherData[...] },
{ target: random.text.cpu-pct-2, otherData[...] },
{ target: random.text.example-0, otherData[...] },
{ target: random.text.example-1, otherData[...] },
{ target: random.text.memory, otherData[...] },
...
]
I want all the objects with a target that includes the string cpu-pct to come first, then the objects with a target that includes the string memory, then example. This array could have any number of items, so re-sorting by index won't work. There could be 1 object with a target that includes cpu-pct, or there could be 50+. Same goes for the other strings I'm sorting by.
I thought about looping over the original array, checking if the desired string exists, saving the matching objects to new arrays for each target I'm looking for, then merging the arrays at the end. I think that would work, but I'd imagine there is a better, more efficient solution, probably using usort, but I'm at a loss. Any ideas?
cpu-pct-0appear before thiscpu-pct-1? And will thetargetalways contain one ofcpu-pct,memeryorexample?-1,0, or1as its response when comparing two items. The examples in that page will help. Try this first, then feel free to post a second question with samples of your code attempts.cpu-pct-0should appear first and go in ascending order according to the number at the end. Forgot to mention, but there will also be acpu-pct-avg, which should appear after the othercpu-pctvalues