Sort array values ​​from a number of segments

I have an array of URLS

For instance:

['support/maintenance', 'support/', 'support/faq/laminator']

How do I sort a database from among segments?

Expected Result:

['support/faq/maninator', 'support/maintenance, 'support/']
+4
source share
9 answers

I see that you have already chosen the answer, and there are 8 more answers, but, nevertheless, I will give you a more elegant Laravel solution (since you are using the framework). Use the method sortByDesc():

collect($array)->sortByDesc(function($i) { return count(explode('/', $i)); });

One readable line.

You can iterate over the result, as you will iterate over a regular array. But if you need an array for some reason, add ->toArray()to the end.

If you want to remove /from the beginning and end of each line when counting segments, add trim($i, '/')a closure like thisexplode('/', trim($i, '/'))

+1
source

arsort, , usort .

<?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);
+6

usort , ( /):

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/
)
*/
+3

URL-

    function count_segment($str) {
        $path = trim($str, '/');
        return count(explode('/', $path));      
    }

   function arrange($a, $b) {
      if ($a == $b) {
        return 0;
       }
       return count_segment($b)-count_segment($a);
   }  

usort($arr, 'arrange');

,

+2

<?php 
$ar = ['support/maintenance', 'support/', 'support/faq/laminator'];
for($i = 0;$i<sizeof($ar);$i++)
{ 
    for($j=$i+1;$j<sizeof($ar);$j++) {

        if(sizeof(explode("/",rtrim($ar[$i],"/")))<sizeof(explode("/",rtrim($ar[$j],"/"))))
        {
            $temp = $ar[$i];
            $ar[$i]= $ar[$j];
            $ar[$j]=$temp;
        }
    }
}
print_r($ar);
+2

...

<?php
    $array = array('support/maintenance', 'support/', 'support/faq/laminator');
    $new = array();
    foreach($array as $r){
        $key = explode('/',$r);//convert the element into array by '/' occurence.
        $key = count(array_filter($key));//remove the empty elements of $key array and count elements.
        $new[$key][] = $r; //assign that row to $new[$key] array. This is because of '/' same occurrence.
    }
    krsort($new); sort $new array by key in descending order
    $final = array_merge(...$new); merge $new array. $final array has your result.
    echo '<pre>';print_r($final);
?>
+2

'/', -, '/'. php, - :

for(let i = 0; i < arr.length; ++i) {
    arr[i].split('/')
}
// possibly bubble sort depending on length of array by highest length
// same loop with a join instead of a split
0
$urlArray = array('support/maintenance', 'support/', 'support/faq/laminator');

foreach ($urlArray as $val){

    $countExploded[] = count(array_filter(explode('/', $val)));

}

asort($countExploded);
$sortedUrlArray = array_replace($countExploded, $urlArray);

print_r($sortedUrlArray);
0

/, .

var_dump(explode('/', 'support/'));

: array(2) { [0]=> string(7) "support" [1]=> string(0) "" }

, 2! .

:

To fix this, we need to trim the string first. Instead of using count(), explodeand trim. We will use only substring_count()and trim().

Here is the whole code:

function sort_url($a, $b)
{
    if ($a == $b) {return 0;}
    return substr_count(trim($a,'/'),'/') > substr_count(trim($b,'/'),'/') ? -1 : 1;
}
$array = ['support/maintenance', 'support/', 'support/faq/laminator'];
usort($array, "sort_url");
print_r($array);

Output

Array ( [0] => support/faq/laminator [1] => support/maintenance [2] => support/ )
0
source

Source: https://habr.com/ru/post/1691488/


All Articles