Sorting an array in order of the value of another array in php
Is there a better way to sort the $ datas array in the order of the $ tabdocids values?
foreach ( $tabdocids as $ordered_id ) {
foreach ( $datas as $doc )
if ($doc->docid == $ordered_id)
$ordered [] = $doc;
}
$datas=$ordered;
+3
Matoeil
source
to share
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
JustOnUnderMillions
source
to share
Try this, it uses single loop over $ datas using map for tabdocids
$flipeddocids=array_flip(tabdocids);
$ordered = [];
foreach ( $datas as $doc ) {
$ordered[$flipeddocids[$doc->docid]]=$doc;
}
$datas=$ordered;
+2
siddharth bhatia
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
Kris roofe
source
to share