Home > Net >  Sort a subArray by based on order of Array in php?
Sort a subArray by based on order of Array in php?

Time:03-18

I have a big array as $orderArr:

$orderArr = array("IZQ", "AOH", "VNP", "ICW", "IOQ", "BXP", "SHH", "EAY", "ZAF", "CUW");

which looks like

Array ( [0] => IZQ [1] => AOH [2] => VNP [3] => ICW [4] => IOQ [5] => BXP [6] => SHH [7] => EAY [8] => ZAF [9] => CUW )

and I have two small arrays as $subArr1 and $suBArr2:

$subArr1 = array("VNP", "BXP", "ICW", "IZQ");

$Subarr2 = array("ZAF", "IZQ", "AOH");

looks like

Array ( [0] => VNP [1] => BXP [2] => ICW [3] => IZQ )

Array ( [0] => ZAF [1] => IZQ [2] => AOH )

Both small arrays (sub array) own elements belong to the big array, but without order.

I want to sort two small arrays according to the order of big array, as following:

Array ( [0] => IZQ [1] => VNP [2] => ICW [3] => BXP )

Array ( [0] => IZQ [1] => AOH [2] => ZAF ) 

I am looking for the simplest codes to do it in php. Any suggestions are welcome.

CodePudding user response:

You could use usort to sort based on array position:

usort($subArr1, function ($a, $b) use ($orderArr) {
   return (array_search($a, $orderArr) < array_search($b, $orderArr)) ? -1 : 1;
});

var_dump($subArr1);

CodePudding user response:

Probably the simplest would be to compute the intersection and it will return in the order of the first array:

$subArr1 = array_intersect($orderArr, $subArr1);

That will return with the keys of the first array; if you want to reindex instead:

$subArr1 = array_values(array_intersect($orderArr, $subArr1));
  • Related