search
HomeBackend DevelopmentPHP Tutorialphp 数组这样的排序怎么做

$a = array(
    '1' => 'one',
    '2' => 'two',
    '3' => 'three',
    '4' => 'four',
    '5' => 'five',
    ....
);

$b = array(2,5,4,1,3,.....); // 数组a的key顺序

$c = array(
    '2' => 'two',
    '5' => 'five',
    '4' => 'four',
    '1' => 'one',
    '3' => 'three',
    ....
);

如何将数组a按照数组b值中key的顺序重新排序得到数组c?(可以不用循环么?)

回复内容:

$a = array(
    '1' => 'one',
    '2' => 'two',
    '3' => 'three',
    '4' => 'four',
    '5' => 'five',
    ....
);

$b = array(2,5,4,1,3,.....); // 数组a的key顺序

$c = array(
    '2' => 'two',
    '5' => 'five',
    '4' => 'four',
    '1' => 'one',
    '3' => 'three',
    ....
);

如何将数组a按照数组b值中key的顺序重新排序得到数组c?(可以不用循环么?)

楼上的答案都是正确的 ... 不过不够帅 ... 我画蛇添足一下好了 ...

如果原数组的键值不是数字而是字符串的话 ... 这样的排序可以一行解决 ...

<?php /* the original array with string keys ... */
$src = [
    'a'   =>  'foo',
    'b'   =>  'bar',
    'c'   =>  'baz',
];

/* the order array ... */
$order = [ 'b', 'a', 'c' ];

/* sort using single line ... */
print_r( array_merge( array_flip( $order ), $src ) );

但是 array_merge() 这个函数有个倒霉特性 ...

当原数组的键值整形化之后不为零的时候 ... 不论原来的键值是什么顺序都会被这个函数全部丢弃 ...

所以你的需求没办法用这种简单的方式解决 ... 只能借助于排序函数 ... 代码如下 ...

<?php /* the original array with integer keys ... */
$src = [
    '1'  =>  'foo',
    '2'   =>  'bar',
    '3'   =>  'baz',
];

/* the order array ... type is not important ... */
$order = [ 1, '3', 0b10 ];

/* get order weight ... */
$weight = array_flip( $order );

/* we do not want to change the source array order huh ..? */
$dst = $src;

/* 3 lines sorting ... not very difficult ... */
uksort( $dst, function( $left, $right ) use ( $weight ) {

    /* $left never equals to $right ... so 0 is impossible ... */ 
    return ( $weight[$left] <p>这种方式虽然写起来复杂 ... 但时间复杂度要低于楼上的整个遍历重生成新数组 ...</p><p>所以效率更高 ... 并且如果需要更改排序方式的话也更加灵活 ...</p><p>恩 ... 就是这样啦 ...</p>
                            
            <p class="answer fmt" data-id="1020000000185778">
                                    </p><pre class="brush:php;toolbar:false">$a = array(
    '1' => 'one',
    '2' => 'two',
    '3' => 'three',
    '4' => 'four',
    '5' => 'five',
    ....
);

$b = array(2,5,4,1,3,.....); // 数组a的key顺序

$c = array();

foreach( $b as $d ) $c[$d] = $a[$d];

print_r( $c );

<code>$a = array(
    '1' => 'one',
    '2' => 'two',
    '3' => 'three',
    '4' => 'four',
    '5' => 'five'
);

$b = array('2','5','4','1','3'); // 数组a的key顺序


$result=array();

function sort_key($v){
    global $result;
    global $a;
    $result[$v]=$a[$v];
}

array_walk($b, 'sort_key');

print_r($result);

</code>

闲着蛋疼写了一个...虽然已经时隔将近2年了...

代码写得矬,期待优雅代码。

$a = array(
    '1' => 'one',
    '2' => 'two',
    '3' => 'three',
    '4' => 'four',
    '5' => 'five',
    ...
);
$b = array(2, 5, 4, 1, 3, ...);
$c = array();

foreach ($b as $v) {
    $c[$v] = $a[$v];
}
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
What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

How do you optimize PHP applications for performance?How do you optimize PHP applications for performance?May 08, 2025 am 12:08 AM

TooptimizePHPapplicationsforperformance,usecaching,databaseoptimization,opcodecaching,andserverconfiguration.1)ImplementcachingwithAPCutoreducedatafetchtimes.2)Optimizedatabasesbyindexing,balancingreadandwriteoperations.3)EnableOPcachetoavoidrecompil

What is dependency injection in PHP?What is dependency injection in PHP?May 07, 2025 pm 03:09 PM

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

Best PHP Performance Optimization TechniquesBest PHP Performance Optimization TechniquesMay 07, 2025 pm 03:05 PM

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

PHP Performance Optimization: Using Opcode CachingPHP Performance Optimization: Using Opcode CachingMay 07, 2025 pm 02:49 PM

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

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 Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.