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 8419381
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T02:35:39+00:00 2026-06-10T02:35:39+00:00

There are numerous questions here asking how to sort a multi-dimensional array in PHP.

  • 0

There are numerous questions here asking how to sort a multi-dimensional array in PHP. The answer is usort(). I know that. But I have a question that takes it a bit further, and I couldn’t see a similar answer here.

I have an array of records, each of which includes a country ID (or a country name if you prefer; it’s not relevant).

My task is to sort the array in such a way as to favour certain countries. This is dynamic — ie the choice of countries to favour is determined by the user’s config. I have a separate array which specifies the required sort order for the first few countries; results from other countries would just be left unsorted at the end of the list.

So the question is: how do I get the this sort criteria into usort() without resorting to using a global variable. And preferably without injecting the criteria array into every element of the main array (‘coz if I’m going to loop it anyway, what’s the point in using usort() at all?)

Please note: Since it’s going to be relevant to the answers here, I’m stuck on PHP 5.2 for the time being, so I can’t use an anonymous function. We are in the process of upgrading, but for now I need answers that will work for 5.2. (answers for 5.3/5.4 will be welcome too, especially if they make it significantly easier, but I won’t be able to use them)

  • 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-06-10T02:35:41+00:00Added an answer on June 10, 2026 at 2:35 am

    You explicitly write that you do not want to have global variables, so I do not make you a suggestion with static variables as well because those are actually global variables – and those are not needed at all.

    In PHP 5.2 (and earlier) if you need call context within the callback, you can create your context by making use of a class of it’s own that carries it:

    class CallContext
    {
    }
    

    For example you have the compare function for sort:

    class CallContext
    {
        ...
        public function compare($a, $b)
        {
             return $this->weight($a) - $this->weight($b);
        }
    
        public function getCallback()
        {
             return array($this, 'compare');
        }
        ...
    }
    

    That function can be used as the following as a callback with usort then:

    $context = new CallContext();
    
    usort($array, $context->getCallback());
    

    Pretty straight forward. The private implementation of CallContext::weight is still missing, and from your question we know it needs some sort data and information. For example the name of the key of the country id in each record. Lets assume records are Stdclass objects so to get the weight of one record the context class needs to know the name of the property, the sort-order you define your own and a sort-value for those country-ids that are not defined in the custom sort order (the others, the rest).

    These configuration values are given with the constructor function (ctor in short) and are stored as private members. The missing weight function then converts a record into the sort-value based on that information:

    class CallContext
    {
        private $property, $sortOrder, $sortOther;
    
        public function __construct($property, $sortOrder, $sortOther = 9999)
        {
            $this->property = $property;
            $this->sortOrder = $sortOrder;
            $this->sortOther = $sortOther;
        }
    
        private function weight($object) {
            if (!is_object($object)) {
                throw new InvalidArgumentException(sprintf('Not an object: %s.', print_r($object, 1)));
            }
            if (!isset($object->{$this->property})) {
                throw new InvalidArgumentException(sprintf('Property "%s" not found in object: %s.', $this->property, print_r($object, 1)));
            }
            $value = $object->{$this->property};
            return isset($this->sortOrder[$value])
                   ? $this->sortOrder[$value]
                   : $this->sortOther;
        }
        ...
    

    The usage now extends to the following:

    $property = 'country';
    $order = array(
        # country ID => sort key (lower is first)
        46 => 1,
        45 => 2
    );
    $context = new CallContext('country', $order);
    usort($array, $context->getCallback());
    

    With the same principle you can very often convert any PHP 5.3 closure with use clauses to PHP 5.2. The variables from the use clause become private members injected with construction.

    This variant does not only prevent the usage of static, it also makes visible that you have got some mapping per each element and as both elements are treated equal, it makes use of a private implementation of some weight function which works very well with usort.

    I hope this is helpful.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I realise there are numerous questions on here asking about choosing between XNA and
I know there have been numerous questions here about inline sql vs stored procedures...
There are numerous discussions here that have addressed issues that seem related to this
I'm aware that similar questions on SO are numerous, but I have a caveat.
I know questions like this have been asked numerous times, but not quite this
Numerous other questions ( here , here and here ) have pointed out that
There are numerous questions on SO similiar to this but not exactly as far
I know there are hundreds of questions about this, but I need to get
Possible Duplicate: What is the Java equivalent for LINQ? There are numerous questions asking
We host our own private NuGet Feed. I've noticed that when there are numerous

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.