根据段数对数组值进行排序

时间:2017-12-29 03:55:46

标签: php laravel

我有一个URLS数组

例如:

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

如何根据细分数量对其进行排序?

预期结果:

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

9 个答案:

答案 0 :(得分:6)

使用 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);

答案 1 :(得分:3)

你应该使用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/
)
*/

答案 2 :(得分:2)

您可以使用此功能计算每个网址细分,并根据此

进行排序
    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');

尝试使用此段数

对数组中的值进行排序

答案 3 :(得分: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);

答案 4 :(得分: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);
?>

答案 5 :(得分:1)

我可以看到你已经选择了答案,还有8个答案,但是,我仍然会给你更优雅的Laravel解决方案(因为你正在使用这个框架)。使用sortByDesc()收集方法:

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

一条可读行。

您可以迭代结果,就像迭代常规数组一样。但如果由于某种原因需要数组,最后添加->toArray()

如果要在计算细分时从每个字符串的开头和结尾删除/,请将trim($i, '/')添加到闭包中,如explode('/', trim($i, '/'))

答案 6 :(得分:0)

您可以将每个元素拆分为&#39; /&#39;然后按子阵列的长度对数组进行排序,然后将子阵列加到&#39; /&#39;上。我不是非常熟悉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

答案 7 :(得分:0)

jkm_df.loc[(:, 201506), :]
            ^
SyntaxError: invalid syntax

答案 8 :(得分:0)

要执行此操作,我们需要删除/以避免获取错误的值。

示例

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

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

如您所见,它返回 2 !这是错误的。

<强>解决方案:

要解决此问题,我们需要先修剪字符串。而不是使用count()explodetrim。我们只会使用substring_count()trim()

以下是整个代码:

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);

<强>输出

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