简体   繁体   English

laravel-sortBy()无法正常工作

[英]laravel - sortBy() not working properly

I have collection with subcollections like: 我有像这样的子集合的集合:

+
+--- name: 1a8 Lorem Ipsum
+
+--- name: 1a2 Lorem Ipsum
+
+--- name: 1a10 Lorem Ipsum

and now I want to sort it by this name: 现在我想用这个名字来排序:

$collection->sortBy('name')

It should be: 它应该是:

1a2 Lorem Ipsum
1a8 Lorem Ipsum
1a10 Lorem Ipsum

but I'm getting: 但我得到:

1a10 Lorem Ipsum
1a2 Lorem Ipsum
1a8 Lorem Ipsum

Why? 为什么? I have tried too with $collection->sortBy('name', SORT_NATURAL, false) but it's same effect. 我也尝试过$collection->sortBy('name', SORT_NATURAL, false)但效果相同。

What might be happening is that because your values are starting with an integer, is that they are turned into an integer value. 可能发生的情况是,因为您的值以整数开头,所以将它们转换为整数值。 That means anything after the first non-numeric character is discared. 这意味着第一个非数字字符被舍弃后的所有内容。 In your case you're left with 3 1 's 在您的情况下,您还有3个1

You might want to use a custom sorting callback that implements strnatcmp 您可能要使用实现strnatcmp的自定义排序回调

$collection->sort(function($a, $b) {
   // using 3 = for type and value comparisan.
   if($a->name === $b->name) {
      return 0;
   };
   return strnatcmp($a->name, $b->name);
});

The solution is already in the answer by @Tschallacka. @Tschallacka的答案已经在解决方案中。 if you want an explanation of why is this happening let me explain. 如果您想解释为什么会发生,请让我解释一下。

The function sortBy is receiving a string . 函数sortBy正在接收string String sorting is analyzed column by column (char position by char position). 字符串排序是逐列分析的(char位置按char位置)。 Integer or numeric type sorting, is analyzed by value. 整数或数字类型排序,按值进行分析。

So if we try to sort: 1,2,3,4,5,6,7,8,9,10,11,12,13... as string we would get something like: 1,10,11,..2,20,21. 因此,如果我们尝试排序: 1,2,3,4,5,6,7,8,9,10,11,12,13...作为字符串,我们将得到类似: 1,10,11,..2,20,21.

Since you are mixing both, you need a solution like the one given already. 由于您将两者混合使用,因此需要一种已经给出的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM