0

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.

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.

2 Answers 2

2

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

Comments

1

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);

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.