【问题标题】:Sorting a collection according to the child with shortest string length根据字符串长度最短的孩子对集合进行排序
【发布时间】:2020-07-08 04:07:47
【问题描述】:

我使用的是 laravel 5.7。

我有一个父类“用户”,它可以有很多孩子“cmets”。 我正在尝试根据 cmets 的字符串长度对集合进行排序,如果用户有任何短字符串,则无论他的其他字符串有多长,用户都会出现在集合的早期。

目前我有这段代码,当用户只有一条评论时,它可以正常工作。但是当他们有多个字符串时,它会选择每个用户可用的最长字符串(或者它可能正在计算用户的总字符串长度?)进行排序,而不是最短的字符串

$collection = User::with('comments')->get();
$comment_length = 'comments.questions';
$collection = $collection->sortBy(function($comment_length) { return strlen($comment_length );});

如果我有的话

user1->comment1 = "srt"
user1->comment2 = "superduperveryverylong"

user2->comment1 = "short"

user3->comment1 = "longer1"
user3->comment2 = "longer2"
user3->comment3 = "longer3"

我希望订单为 [1,2,3] 但得到 [2,3,1]。 cmets个数无关(>0时)

任何想法如何为这种情况编写排序函数?

提前致谢!

【问题讨论】:

    标签: laravel sorting


    【解决方案1】:

    你可以通过 php 的usort 函数来实现。

    // Used to determine the max length of a users comments
    $maxCommentLength = function ($max, $comment) {
       $length = strlen($comment->???);
       if ($length > $max) {
           return $length;
       }
         
       return $max;
    };
    
    // Sort the users array using a comparator function and our max length helper
    $sorted = usort($users, function ($u1, $u2) use ($maxCommentLength) {
        $max1 = $u1->comments->reduce($maxCommentLength, 0);
        $max2 = $u2->comments->reduce($maxCommentLength, 0);
        
        // Shift element right
        if ($max1 > $max2) {
            return 1;
        }
        
        // Shift element left
        if ($max1 < $max2) {
            return -1;
        }
        
        // Keep same index
        return 0;
    });
    

    【讨论】:

    • 非常感谢!我需要稍微修改一下算法以找到最短的注释(而不是最长的注释),并使用 $collection->sort() 而不是 usort 因为它是一个对象而不是数组,但这起到了作用。 :)
    • 干得好!很高兴为您提供帮助。
    猜你喜欢
    • 2018-02-23
    • 2013-11-05
    • 1970-01-01
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-13
    相关资源
    最近更新 更多