Heim >Backend-Entwicklung >PHP-Tutorial >php 数组这样的排序怎么做
$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]; }