-2
$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)

2
  • You want to sort of FILTER your array ? Commented Mar 9, 2017 at 12:42
  • yeah kind of that, values from a will ordered exactly by array , if values from a is not there in b then, it won't consider, and if there is extra values in a then order of that values in a should not be changed Commented Mar 9, 2017 at 12:47

1 Answer 1

0

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]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.