Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

php - sort an array according to second given array

$a = array('val1','val2',200, 179,230, 234, 242); 
$b = array(230, 234, 242, 179, 100);

So array $a should be sorted according to array $b and $resultArray should be ('val1','val2',200, 230, 234, 242, 179)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your sorting requirements:

  1. values not found in the sorting array come before values that ARE found.
  2. then:
    1. sort found values by their position in the sorting array
    2. sort values not found in the sorting array normally/ascending

Flipping your order lookup array will permit improved efficiency while processing before key searching is faster than value searching in php.

Code: (Demo)

$array = ['val1', 'val2', 200, 179, 230, 234, 242]; 
$order = [230, 234, 242, 179, 100];
$keyedOrder = array_flip($order); // for efficiency

usort($array, function($a, $b) use ($keyedOrder) {
    return [$keyedOrder[$a] ?? -1, $a]
           <=>
           [$keyedOrder[$b] ?? -1, $b];
});
var_export($array);

Output:

array (
  0 => 'val1',
  1 => 'val2',
  2 => 200,
  3 => 230,
  4 => 234,
  5 => 242,
  6 => 179,
)

$keyedOrder[$variable] ?? -1 effectively means if the value is not found in the lookup, use -1 to position the item before the lowest value in the lookup array (0). If the value IS found as a key in the lookup, then use the integer value assigned to that key in the lookup.


From PHP7.4, arrow function syntax can be used to make the snippet more concise and avoid the use() declaration.

Demo

usort($array, fn($a, $b) => [$keyedOrder[$a] ?? -1, $a] <=> [$keyedOrder[$b] ?? -1, $b]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...