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

  • Home
  • SEARCH
  • 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 553847
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T11:38:52+00:00 2026-05-13T11:38:52+00:00

I am currently creating a sorting method that consists of values from an mysql

  • 0

I am currently creating a sorting method that consists of values from an mysql query.

Here’s a brief view of the array:

    Array
    (
        [0] => Array
            (
                ['id'] = 1;
                ['countries'] = 'EN,CH,SP';
            )
        [1] => Array
            (
                ['id'] = 2;
                ['countries'] = 'GE,SP,SV';
            )
    )

I have succeeded in making a normal usort based on the numeric id values, but I rather want to sort the array by the content of the “countries” field (if it contains a set string, a country code in this case), and then by the id field.

The following snippet was my first idea of how to do it, but I have no idea of how to incorporate it into an working function:

in_array('EN', explode(",",$a['countries']) );

How would you do it?

Thanks!


I am really getting nowhere with this unfortunately.

Here is what I have for the moment, and its giving me nothing but errors: uasort() [function.uasort]: Invalid comparison function

function compare($a, $b) {
    global $usercountry;

        if ( in_array($usercountry, $a['countries']) && in_array($usercountry, $a['countries']) ) {
            $return = 0;
        }

        else if (in_array($usercountry, $a['countries'])) {
            $return = 1;
        }

        else {
            $return = -1;
        }

        return $return;


        }

        $array= usort($array, "compare");

Is there anyone who might give me a hint of how to go on with it?

  • 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-13T11:38:52+00:00Added an answer on May 13, 2026 at 11:38 am

    Personally, I would use a custom (anonymous) function in conjunction with usort().

    EDIT: Re – your comment. Hopefully this will put you on the right track. This function gives equal priority to elements which both have EN or neither have EN, or adjusted priority when just one has EN.

    usort($array,function ($a, $b) {
        $ac = strpos($a['countries'],'EN');
        $bc = strpos($b['countries'],'EN');
        if (($ac !== false && $bc !== false) || ($ac == false && $bc == false)) {
            return 0;
        }
        elseif ($ac !== false) {
            return 1;
        }
        else {
            return -1;
        }
    });
    

    This function, on the other hand, gives equal priority if both have EN, higher if one has EN, and does a text comparison if neither has EN.

    usort($array,function ($a, $b) {
        $ac = strpos($a['countries'],'EN');
        $bc = strpos($b['countries'],'EN');
        if ($ac !== false && $bc !== false)) {
            return 0;
        }
        elseif ($ac !== false) {
            return 1;
        }
        elseif ($bc !== false) {
            return -1;
        }
        else {
            if ($a['countries'] == $b['countries']) {
                return 0;
            }
            elseif($a['countries'] > $b['countries']) {
                return 1;
            }
            else {
                return -1;
            }
        }
    });
    

    Again, hopefully this will give you enough direction to move forward on your own. If you are having any problems, feel free to post more comments and I’ll try to help. A note if you’re tying to compare multiple properties with weight: try out a funky switch block, e.g.

    $ac = array_flip(explode(',',$a['countries']));
    $bc = array_flip(explode(',',$b['countries']));
    switch (true) {
        case array_key_exists('EN',$ac) && !array_key_exists('EN',$bc):
            return 1;
        case array_key_exists('DE',$ac) && !array_key_exists('EN',$bc) && !array_key_exists('EN',$bc):
            return 1;
        // and so on
    }
    

    #More Edits!#
    Actually, I was thinking more on the problem of complex sorting, and I have come up with the following solution, for your consideration. It will allow you to define numerical rankings based on keywords which would appear in the countries index. Here is the code, including an example:

    Example Array

    $array = array(
        array(
            'countries' => 'EN,DE,SP',
        ),
        array(
            'countries' => 'EN,CH,SP',
        ),
        array(
            'countries' => 'DE,SP,CH',
        ),
        array(
            'countries' => 'DE,SV,SP',
        ),
        array(
            'countries' => 'EN,SP,FR',
        ),
        array(
            'countries' => 'DE,FR,CH',
        ),
        array(
            'countries' => 'CH,EN,SP',
        ),
    
    );
    

    Sorting Routine

    $rankings = array(
        'EN' => 10,
        'SP' => 8,
        'FR' => 7,
        'DE' => 5,
        'CH' => 3,
        'SV' => 1,
    );
    usort($array, function (&$a, &$b) use ($rankings) {
        if (isset($a['_score'])) {
            $aScore = $a['_score'];
        }
        else {
            $aScore = 0;
            $aCountries = explode(',',$a['countries']);
            foreach ($aCountries as $country) {
                if (isset($rankings[$country])) {
                    $aScore += $rankings[$country];
                }
            }
            $a['_score'] = $aScore;
        }
    
        if (isset($b['_score'])) {
            $bScore = $b['_score'];
        }
        else {
            $bScore = 0;
            $bCountries = explode(',',$b['countries']);
            foreach ($bCountries as $country) {
                if (isset($rankings[$country])) {
                    $bScore += $rankings[$country];
                }
            }
            $b['_score'] = $bScore;
        }
        if ($aScore == $bScore) {
            return 0;
        }
        elseif ($aScore > $bScore) {
            return -1;
        }
        else {
            return 1;
        }
    });
    

    Note: This code will sort the highest ranking entires to the top of the array. If you want reverse behavior, change this:

        elseif ($aScore > $bScore) {
    

    to

        elseif ($aScore < $bScore) {
    

    Note that the greater-than was changed to a less-than symbol. Making this change will result in the lowest ranking entries being sorted to the top of the array. Hope all this helps!

    ##NOTE ALSO!##
    This code will make a small change to your array, in that it adds the _score element to each array. Hopefully this is not a problem, as by storing this value I was literally able to increase speed by more than double (.00038-.00041 down to .00016-.00018 in my benchmarks). If not, remove the if blocks that retrieve the cached value and let the contents of the else blocks execute every time, except of course for the part which stores the score value.

    By the way, here’s a var_export() dump of the array after it was sorted:

    array (
      0 => array (
        'countries' => 'EN,SP,FR',
        '_score' => 25,
      ),
      1 => array (
        'countries' => 'EN,DE,SP',
        '_score' => 23,
      ),
      2 => array (
        'countries' => 'EN,CH,SP',
        '_score' => 21,
      ),
      3 => array (
        'countries' => 'CH,EN,SP',
        '_score' => 21,
      ),
      4 => array (
        'countries' => 'DE,SP,CH',
        '_score' => 16,
      ),
      5 => array (
        'countries' => 'DE,FR,CH',
        '_score' => 15,
      ),
      6 => array (
        'countries' => 'DE,SV,SP',
        '_score' => 14,
      ),
    )
    

    Enjoy!

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

Sidebar

Ask A Question

Stats

  • Questions 303k
  • Answers 303k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer I'd suggest you go with SLF4J instead to decouple your… May 13, 2026 at 8:35 pm
  • Editorial Team
    Editorial Team added an answer __NAMESPACE__ is a compile time constant, meaning that it is… May 13, 2026 at 8:35 pm
  • Editorial Team
    Editorial Team added an answer first, what are these files? The vshost.exe files are hosting… May 13, 2026 at 8:34 pm

Related Questions

I am using C# and .NET 3.5 and have a GridView that I am
I am creating a series of arrays from template tags in a content management
I am currently creating a mobile version of my company's site and using it
I am currently creating a small table in Oracle and am unsure of which
I am currently creating a web site with pure HTML ( No frameworks Just

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.