I have an array of URLS
Eg:
['support/maintenance', 'support/', 'support/faq/laminator']
How do I sort it base from the number of segments?
Expected result:
['support/faq/maninator', 'support/maintenance, 'support/']
Use arsort to organize in reverse order, then use usort to sort by string size.
<?php
$arr = ['support/maintenance', 'support/', 'support/faq/laminator'];
function sortOrder($currentValue, $nextValue) {
$totalSegmentsOfTheCurrentIndex = count(preg_split('/\//', $currentValue, -1, PREG_SPLIT_NO_EMPTY));
$totalSegmentsOfTheNextIndex = count(preg_split('/\//', $nextValue, -1, PREG_SPLIT_NO_EMPTY));
// The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
return $totalSegmentsOfTheNextIndex - $totalSegmentsOfTheCurrentIndex;
}
usort($arr, 'sortOrder');
var_export($arr);
You should use usort with custom comparator to count the number of segments after exploding each element by the divider (which is an /
in this case):
function comparator($a, $b)
{
if ($a == $b) {
return 0;
}
return count(explode('/', $a)) < count(explode('/', $b)) ? 1 : -1;
}
$array = ['support/maintenance', 'support/', 'support/faq/laminator'];
usort($array, "comparator");
print_r($array);
/**
Array
(
[0] => support/faq/laminator
[1] => support/maintenance
[2] => support/
)
*/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With