Sorting an array in order of the value of another array in php
3 answers
One way for rome ...
#for collect
$ordered = array_flip($tabdocids);//too keep the order from the $tabdocids
array_map(function ($doc) use ($tabdocids,&$ordered){
if(in_array($doc->docid,$tabdocids)){ $ordered [$doc->docid] = $doc; }
},$datas);
$datas=array_values($ordered);
[updated after comment from @Kris Roofe] it will now be sorted.
or without sorting
$datas = array_filter($datas,function ($doc) use ($tabdocids){
return (bool)in_array($doc->docid,$tabdocids);
});
+5
source to share
First, you can calculate the order sequence. Then use the $ datas reordering order, it will reduce the number of computations.
$order = array_flip(array_values(array_unique(array_intersect($tabdocids, array_column((array)$datas, 'docid')))));
usort(&$datas, function($a, $b) use($order){
return isset($order[$a->docid]) ? isset($order[$b->docid]) ? $order[$a->docid] <=> $order[$b->docid] : -1 : (isset($order[$b->docid]) ? 1 : -1);
});
+1
source to share