Sort Multidimensional Array With PHP

Home / Snippets / Sort Multidimensional Array With PHP
Want create site? Find Free WordPress Themes and plugins.

Most of us work with php multidimensional arrays on daily basis. There are times when we need to quickly sort multidimensional array and get results back in a new array. Most will find it a bit tricky. Below is a great solution to solve multidimensional array sorting.


//Lets create a sample multidimensional array:

$unSortedArray['cat1'] = "aArrayItem1";
$unSortedArray['cat2'] = "bArrayItem1";

$unSortedArray['cat1'] = "aArrayItem2";
$unSortedArray['cat2'] = "bArrayItem2";

$unSortedArray['cat1'] = "aArrayItem3";
$unSortedArray['cat2'] = "bArrayItem3";

Next, we will add following function to our code.


function array_sort($array, $on, $order=SORT_ASC)
{
    $new_array = array();
    $sortable_array = array();

    if (count($array) > 0) {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $k2 => $v2) {
                    if ($k2 == $on) {
                        $sortable_array[$k] = $v2;
                    }
                }
            } else {
                $sortable_array[$k] = $v;
            }
        }

        switch ($order) {
            case SORT_ASC:
                asort($sortable_array);
            break;
            case SORT_DESC:
                arsort($sortable_array);
            break;
        }

        foreach ($sortable_array as $k => $v) {
            $new_array[$k] = $array[$k];
        }
    }

    return $new_array;
}

And finally, let’s call this function and store result in a new array.


//Call function and store it in a new array:
$sortedArray = array_sort($unSortedArray, 'cat1', SORT_ASC);
//$sortedArray = array_sort($unSortedArray, 'cat1', SORT_DESC);

As you can see, this is a very quick and simple solution to sort multidimensional arrays. If you find this post helpful, please leave your comments or other possible solutions.

Did you find apk for android? You can find new Free Android Games and apps.

Comments(0)

Leave a Comment