There will be a few ways to skin this cat. All of my methods will produce the expected output...
First, let's do it without restructuring your array (Demo):
$order=["XS","S","M","L","XL","2XL","3XL"]; // declare appropriate size order
$ArrayStock=[["L","XL","M"],["12","3","2"]];
// Order the first subarray:
uasort($ArrayStock[0],function($a,$b)use($order){
return (array_search($a,$order)>array_search($b,$order)?1:-1); // any unidentifed sizes will go to the front
});
// Sync the second subarray with first subarray:
$ArrayStock[1]=array_replace($ArrayStock[0],$ArrayStock[1]);
// Optionally re-index the keys:
$ArrayStock[0]=array_values($ArrayStock[0]);
$ArrayStock[1]=array_values($ArrayStock[1]);
Next I'll show a few ways that you can manipulate a restructured array. There is absolutely nothing wrong with the way that trincot has written his. These are just alternatives that I've come up with...
I agree with trincot about using sizes as keys (because they will be unique) and stock counts as values. So the first process is to generate that new array structure:
$ArrayStock=[["L","XL","M"],["12","3","2"]];
#1 One-liner array_combine() approach:
$new_structure=array_combine($ArrayStock[0],$ArrayStock[1]);
// $new_structure = ['L'=>'12','XL'=>'3','M'=>'2']
#2 foreach() approach:
foreach($ArrayStock[0] as $i=>$size){
$new_structure[$size]=$ArrayStock[1][$i];
}
// $new_structure = ['L'=>'12','XL'=>'3','M'=>'2']
Now to sort the new array, you can use uksort() or a range of other array functions / loops with your predetermined order array:
$order=["XS","S","M","L","XL","2XL","3XL"]; // declare whatever appropriate sizes in order
#1 uksort() with array_search() approach:
uksort($new_structure,function($a,$b)use($order){
return (array_search($a,$order)>array_search($b,$order)?1:-1);
// any unidentified sizes will go to the front of the array
});
// keep in mind, this doesn't declare $result, it sorts $new_structure
#2 array_replace() with array_flip()-array_intersect()-array_keys() approach:
$result=array_replace( // replace values on matching keys
array_flip( // swap keys with values
array_intersect(
$order, // keep values from here
array_keys($new_structure) // that exist here
)
),
$new_structure); // use these elements for replace
// $result=['M'=>'2','L'=>'12','XL'=>'3'];
#3 foreach() with array_intersect()-array_keys() approach:
// generate & iterate ordered array
foreach(array_intersect($order,array_keys($new_structure)) as $v){
$result[$v]=$new_structure[$v]; // build properly sorted array
}
// $result=['M'=>'2','L'=>'12','XL'=>'3'];
Finally as trincot has shown, you can revert the sorted data back to the initial format with one more one-liner:
$ArrayStock=[array_keys($result),array_values($result)];
usort()function