Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array values base from the number of segments

Tags:

php

laravel

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/']
like image 555
Kerwin Avatar asked Dec 04 '22 20:12

Kerwin


2 Answers

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);
like image 82
Valdeir Psr Avatar answered Dec 11 '22 15:12

Valdeir Psr


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/
)
*/
like image 40
Adam Szmyd Avatar answered Dec 11 '22 16:12

Adam Szmyd