search
HomeBackend DevelopmentPHP Tutorialjavascript - For Olympic medals, how to determine the national ranking according to the order of gold, silver and bronze (see the title for details)

The structure of the data is roughly like this

<code> $arr = [
          ['name'=>'国家一','score'=>[10,7,5]],
          ['name'=>'国家二','score'=>[10,9,5]],
          ['name'=>'国家三','score'=>[11,7,5]],
          ['name'=>'国家四','score'=>[10,7,9]],
        ];
</code>

The sorting rule is, gold medals are compared first, gold medals are always better than silver medals, silver medals are always better than bronze medals, bronze medals are always better than id, and id is the initial array sequence number

The three numbers in the score represent the amount of gold, silver and copper respectively

Those that require less use of built-in functions are best implemented in PHP

Reply content:

The structure of the data is roughly like this

<code> $arr = [
          ['name'=>'国家一','score'=>[10,7,5]],
          ['name'=>'国家二','score'=>[10,9,5]],
          ['name'=>'国家三','score'=>[11,7,5]],
          ['name'=>'国家四','score'=>[10,7,9]],
        ];
</code>

The sorting rule is, gold medals are compared first, gold medals are always better than silver medals, silver medals are always better than bronze medals, bronze medals are always better than id, and id is the initial array sequence number

The three numbers in the score represent the amount of gold, silver and copper respectively

Those that require less use of built-in functions are best implemented using PHP

There are three numbers that represent the number of medals. Can you at least tell me what the sorting rules are?

Is it the total number of medals? According to gold, silver and copper respectively? Or some strange permutation?


There are many ways. The lazy way is to compare four times directly. First sort by gold medal, select the ones with the same gold medal, and then sort by silver medal among the same ones... and so on

If you want to sort them at once, just change the gold, silver, and copper serial numbers into a number to sort them.
For example, your array can become like this——

<code>[010007005001,010009005002,011007005003,010007009004]</code>

The rules are very simple. Fill in the gold, silver, and copper serial numbers to three digits, then directly splice them together. Finally, just sort the group of numbers directly, and it will be done in one go.

PHP array_multisort implements sorting by multiple fields like SQL ORDER BY.
For example, the Olympic medal list is sorted in descending order by the number of gold medals, silver medals, and bronze medals.

<code><?php header('Content-Type: text/plain; charset=utf-8');
$arr = array(
    '中国' => array(
        '金牌' => 8,
        '银牌' => 3,
        '铜牌' => 6,
    ),
    '俄罗斯' => array(
        '金牌' => 3,
        '银牌' => 6,
        '铜牌' => 3,
    ),
    '美国' => array(
        '金牌' => 6,
        '银牌' => 8,
        '铜牌' => 8,
    ),
    '澳大利亚' => array(
        '金牌' => 4,
        '银牌' => 0,
        '铜牌' => 4,
    ),
    '意大利' => array(
        '金牌' => 3,
        '银牌' => 4,
        '铜牌' => 2,
    ),

);
// 实现 ORDER BY
foreach($arr as $k => $v) {
    $sort['金牌'][$k] = $v['金牌'];
    $sort['银牌'][$k] = $v['银牌'];
    $sort['铜牌'][$k] = $v['铜牌'];
}
array_multisort(
    $sort['金牌'], SORT_DESC, 
    $sort['银牌'], SORT_DESC, 
    $sort['铜牌'], SORT_DESC, 
    $arr);
var_export($arr);</code>

Let’s make a python version, assuming that the number of each type of medals in each country will not exceed 999.

<code>arr = [
    {'name':'国家一','score':[10,7,5]},
    {'name':'国家二','score':[10,9,5]},
    {'name':'国家三','score':[11,7,5]},
    {'name':'国家四','score':[10,7,9]},
]

print sorted(arr, key=lambda a: '%03d%03d%03d' % tuple(a['score']), reverse=True)</code>

score is best separated when designing.
Design a class (including country, gold, silver, and bronze numbers), implement the Comparable interface, and implement the compare method according to the rules you described. Isn't it simple?

Gold Medal + Silver Medal + Bronze Medal + ID form a number and then sort it directly. For example, id13-[10, 2, 20] forms 10022013, and then sort it directly according to this number

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use