user2881966 user2881966 - 2 months ago 10
PHP Question

Sorting multiple strings into an order

I need an help on my php code

I got string array. It contains multiple values inside. Such as 'XXL', 'X', '1', '1.5','2', '3', 'T', '1K','1.5K','5K','Adult','One Size'.

Now I want it to be sorted as follows.
2T, 3T, 4T, YXXS, YXS, YS, YM, YL, YXL, XXS, XS, S, M, L, XL, XXL, XXXL, WXXS, WXS, WS, WM, WL, WXL, WXXL, Youth, Adult, One Size, 8K, 8.5K, 9K, 9.5K, 10K, 10.5K, 11K, 11.5K 12K, 12.5K, 13K, 13.5K, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5, 9, 9.5, 10, 10.5, 11, 11.5, 12, 12.5, 13, 13.5, 14, 14.5, 15, Futsal

I need a sorting function or an algorithm to fix this issue

Answer

You can use an array_intersect for this as there is really no logical way to sort these options.

<?php

$sort_order = array('2T', '3T', '4T', 'YXXS', 'YXS', 'YS', 'YM', 'YL', 'YXL', 'XXS', 'XS', 'S', 'M', 'L', 'X', 'XL', 'XXL', 'XXXL', 'WXXS', 'WXS', 'WS', 'WM', 'WL', 'WXL', 'WXXL', 'Youth', 'Adult', 'One Size', '8K', '8.5K', '9K', '9.5K', '10K', '10.5K', '11K', '11.5K 12K', '12.5K', '13K', '13.5K', '1', '1.5', '2', '2.5', '3', '3.5', '4', '4.5', '5', '5.5', '6', '6.5', '7', '7.5', '8', '8.5', '9', '9.5', '10', '10.5', '11', '11.5', '12', '12.5', '13', '13.5', '14', '14.5', '15', 'Futsal');
$sizes      = array('XXL', 'X', '1', '1.5','2', '3', 'T', '1K','1.5K','5K','Adult','One Size');

$sorted_sizes = array_intersect($sort_order, $sizes);

print_r($sorted_sizes);

?>
Comments