Ad

Reindex An Object So Keys Are Sequential

- 1 answer

I am building an object from a laravel collection, the code for this looks like this,

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

This filters through the collection and returns an object that looks like this,

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",…}

I have a problem that I need sequential keys in my object - is this possible?

I know if my object were an array then I would be able to do,

array_values($array)

but I know of nothing similar in php?

Ad

Answer

Basically all array_* functions are also available on Laravel's Collection class, as can be found in the documentation.

As you say you would normally do this using array_values, so all you have to do now is chain the call to filter with a call to values:

$project->briefNotifications = $user->notifications->filter(...)->values();
Ad
source: stackoverflow.com
Ad