【问题标题】:reindex an object so keys are sequential重新索引对象,以便键是顺序的
【发布时间】:2016-03-19 22:52:39
【问题描述】:

我正在从 laravel 集合构建一个对象,代码如下所示,

$project->briefNotifications = $user->notifications->filter(function($notification) use($project){
            if($notification->object_type == "brief" || $notification->object_type == "briefversion" && $notification->is_read == 0 && $notification->parent_id == $project->id) {
                $project->calendarAlerts++;
                return $notification;
            }
        });

这会过滤集合并返回一个看起来像这样的对象,

0: {id: 7283, type: "create", activity: "Stephen saved a new version of the brief",…} 1: {id: 7282, type: "create", activity: "Stephen saved a new version of the brief",…} 2: {id: 7281, type: "create", activity: "Stephen saved a new version of the brief",…} 3: {id: 7280, type: "create", activity: "Stephen saved a new version of the brief",…} 5: {id: 7224, type: "update", activity: "Stephen changed Version 2 of the brief",…}

我有一个问题,我需要在我的对象中使用顺序键 - 这可能吗?

我知道如果我的对象是一个数组,那么我就能做到,

array_values($array)

但我不知道 php 中有什么类似的东西?

【问题讨论】:

    标签: php laravel object indexing collections


    【解决方案1】:

    基本上所有array_* 函数都可以在 Laravel 的 Collection 类中使用,可以在 in the documentation 中找到。

    正如您所说,您通常会使用array_values 执行此操作,因此您现在要做的就是将调用链接到filter 并调用values

    $project->briefNotifications = $user->notifications->filter(...)->values();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-08
      • 2014-03-08
      • 2020-04-17
      • 1970-01-01
      • 2012-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多