Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6324833
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T16:46:49+00:00 2026-05-24T16:46:49+00:00

I’m looking to be able to sort an array of associative arrays on more

  • 0

I’m looking to be able to sort an array of associative arrays on more than one column. To further complicate it, I’d like to be able to set specific sort options per key/column. I have a set of data that is similar to a db query’s result set, but it doesn’t actually come from one so I need to sort it in PHP rather than SQL.

[
    ['first_name' => 'Homer', 'last_name' => 'Simpson', 'city' => 'Springfield', 'state' => 'Unknown', 'zip' => '66735'],
    ['first_name' => 'Patty', 'last_name' => 'Bouvier', 'city' => 'Scottsdale', 'state' => 'Arizona', 'zip' => '85250'],
    ['first_name' => 'Moe', 'last_name' => 'Szyslak', 'city' => 'Scottsdale', 'state' => 'Arizona', 'zip' => '85255'],
    ['first_name' => 'Nick', 'last_name' => 'Riviera', 'city' => 'Scottsdale', 'state' => 'Arizona', 'zip' => '85255'],
];

I would like to be able to sort it similar to what could be done with a DB query. Oh, and sometimes a column/key needs to be specified by number.

What I had in mind was something similar to this:

$sortOptions = array(
    array( 'city', SORT_ASC, SORT_STRING),
    array( 'zip', SORT_DESC, SORT_NUMERIC),
    array( 2, SORT_ASC, SORT_STRING) // 2='last_name'
);
$sorter = new MultiSort($data, $sortOptions);
$sortedData = $sorter->getSortedArray();
print_r($jmsSorted);

What I would like to end up with is this:

Array
(
    [0] => Array
        (
            [first_name] => Nick
            [last_name] => Riviera
            [city] => Scottsdale
            [state] => Arizona
            [zip] => 85255
        )

    [1] => Array
        (
            [first_name] => Moe
            [last_name] => Szyslak
            [city] => Scottsdale
            [state] => Arizona
            [zip] => 85255
        )

    [2] => Array
        (
            [first_name] => Patty
            [last_name] => Bouvier
            [city] => Scottsdale
            [state] => Arizona
            [zip] => 85250
        )

    [3] => Array
        (
            [first_name] => Homer
            [last_name] => Simpson
            [city] => Springfield
            [state] => Unknown
            [zip] => 66735
        )

)

UPDATE: I think that ideally, a solution would result in dynamically creating

array_multisort( $city, SORT_ASC, SORT_STRING, $zip, SORT_DESC, SORT_NUMERIC, $last_name, SORT_ASC, SORT_STRING, $inputArray);

The problem is that I don’t want to have to “hard code” those key names in there. I tried creating a solution based upon Example #3 Sorting database results from the array_multisort() documentation that ended up using array_multisort() but I cannot seem to find a way to use my dynamically built argument list for array_multisort().

My attempt was to “chain” those arguments together into an array and then

call_user_func_array( 'array_multisort', $functionArgs);

That results in an

Warning: Parameter 2 to array_multisort() expected to be a reference, value given in…

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T16:46:50+00:00Added an answer on May 24, 2026 at 4:46 pm

    Here is what I finally settled on for being able to sort multi-dimensional arrays. Both of the answers above are good but I was also looking for something flexible.

    I definitely don’t think there is any one “right” answer, but this is what works for my needs and is flexible.

    As you can see from my @link in the comment of _usortByMultipleKeys() it was adapted from a comment in the PHP manual that currently doesn’t seem to exist, but I believe http://www.php.net/manual/en/function.usort.php#104398 is a new version of the original comment. I have not explored using that new suggestion.

    /**
     * Sort the resultSet.
     *
     * Usage: $sortOptions = array(
     *          'section', // Defaults to SORT_ASC
     *          'row' => SORT_DESC,
     *          'retail_price' => SORT_ASC);
     *        $results->sortResults($sortOptions);
     *
     * @param array $sortOptions    An array of sorting instructions
     */
    public function sortResults(array $sortOptions)
    {
        usort($this->_results, $this->_usortByMultipleKeys($sortOptions));
    }
    
    
    /**
     * Used by sortResults()
     *
     * @link http://www.php.net/manual/en/function.usort.php#103722
     */
    protected function _usortByMultipleKeys($key, $direction=SORT_ASC)
    {
        $sortFlags = array(SORT_ASC, SORT_DESC);
        if (!in_array($direction, $sortFlags)) {
            throw new InvalidArgumentException('Sort flag only accepts SORT_ASC or SORT_DESC');
        }
        return function($a, $b) use ($key, $direction, $sortFlags) {
            if (!is_array($key)) { //just one key and sort direction
                if (!isset($a->$key) || !isset($b->$key)) {
                    throw new Exception('Attempting to sort on non-existent keys');
                }
                if ($a->$key == $b->$key) {
                    return 0;
                }
                return ($direction==SORT_ASC xor $a->$key < $b->$key) ? 1 : -1;
            } else { //using multiple keys for sort and sub-sort
                foreach ($key as $subKey => $subAsc) {
                    //array can come as 'sort_key'=>SORT_ASC|SORT_DESC or just 'sort_key', so need to detect which
                    if (!in_array($subAsc, $sortFlags)) {
                        $subKey = $subAsc;
                        $subAsc = $direction;
                    }
                    //just like above, except 'continue' in place of return 0
                    if (!isset($a->$subKey) || !isset($b->$subKey)) {
                        throw new Exception('Attempting to sort on non-existent keys');
                    }
                    if ($a->$subKey == $b->$subKey) {
                        continue;
                    }
                    return ($subAsc==SORT_ASC xor $a->$subKey < $b->$subKey) ? 1 : -1;
                }
                return 0;
            }
        };
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a jquery bug and I've been looking for hours now, I can't
I would like to count the length of a string with PHP. The string
link Im having trouble converting the html entites into html characters, (&# 8217;) i
For some reason, after submitting a string like this Jack’s Spindle from a text
I've got a string that has curly quotes in it. I'd like to replace
I am reading a book about Javascript and jQuery and using one of the
In my XML file chapters tag has more chapter tag.i need to display chapters
I am trying to render a haml file in a javascript response like so:
I would like to run a str_replace or preg_replace which looks for certain words

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.