Multidimensional Associative Array Sorting in PHP

I needed to sort a deep multidimensional associative array for PlanterApp, so I looked around for some solutions. The one I found was close enough to the right answer that I was able to make it work by defining a function, then referring to that function as follows:

function sortMyTools( $i, $j ) { // function sort the Tools array by [Tool][name]
    $a = $i['Tool']['name'];
    $b = $j['Tool']['name'];
    if ($a == $b) return 0;
        elseif ($a > $b) return 1;
        else return -1;
    uasort($tools, sortMyTools ); // uasort() using the function

Since the enormous $tools array has many levels, this cool code provides a great answer to sorting on the tool name element quite nicely.
Credits to:

Note: uasort — Sort an array with a user-defined comparison function and maintain index association

Latest post: Blog Continues at

Post an Insight

This site uses Akismet to reduce spam. Learn how your comment data is processed.