Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 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 Answer

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]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...