Skip to content
Advertisement

PHP associative array sorting by previous value

I have the following array that I’m trying to sort. The value is where the key should come after in the final output array.

JavaScript

The final output would be like this.

JavaScript

I’ve been trying to wrap my head around an appropriate approach but I seem to be taking myself down the wrong paths. I keep ending up with only some of the elements following the correct rules. How would you tackle this? I tried looping, splicing and searching in many ways with no luck.

Edit: uncleaned attempt

JavaScript

Edit 2: Here are the master lists I built $main from

JavaScript

Advertisement

Answer

Here’s a function that will sort the array the way you want. It is based on @deceze algorithm (described in the comments to the question), using array_diff to find the key which is not also a value, and then iterating back through the array until the key matches the value at that key:

JavaScript

Output of print_r(sorter($main)) for your data:

JavaScript

Demo on 3v4l.org

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement