Once you prepare your priority lookup array it is merely a matter of passing it into usort()'s scope and either using the related priority value or if the key property's value is not in the priority array, then use the fallback value. Readable, direct, and concise.
Code: (Demo)
$objects = [
(object)["name" => "Name1", "key" => "key1"],
(object)["name" => "Name2", "key" => "key2"],
(object)["name" => "Name3", "key" => "key3"],
];
$keys = ["key3", "key1"];
$lookup = array_flip($keys);
$fallback = count($keys);
usort($objects, function($a, $b) use ($lookup, $fallback) {
return ($lookup[$a->key] ?? $fallback) <=> ($lookup[$b->key] ?? $fallback);
});
var_export($objects);
Output:
array (
0 =>
(object) array(
'name' => 'Name3',
'key' => 'key3',
),
1 =>
(object) array(
'name' => 'Name1',
'key' => 'key1',
),
2 =>
(object) array(
'name' => 'Name2',
'key' => 'key2',
),
)
From PHP7.4, the syntax can be further condensed and the use() declaration omitted. (Demo)
usort($objects, fn($a, $b) => ($lookup[$a->key] ?? $fallback) <=> ($lookup[$b->key] ?? $fallback));