johnef_sh's avatar

Group results in array

My query looks like this

I have this query

$getShipments = PickupList::whereUniqueId($uniqueId)->get(['shipment_id']);
        $cities = [];
        foreach ($getShipments as $shipment) {
            $getCity = Shipment::whereId($shipment->shipment_id)->with(['receiver.city'])->first();
            $cities[] = $getCity->receiver->city->name;
        }

it will return something like this array

0 => "city 1"
1 => "city 2"
2 => "city 1"

How could I groupBy the city by city_id in this case?

0 likes
3 replies
LaryAI's avatar
Level 58

To group the cities by their ID, you can modify the existing code to use the groupBy method on the collection. Here's an example:

$getShipments = PickupList::whereUniqueId($uniqueId)->get(['shipment_id']);
$cities = [];
foreach ($getShipments as $shipment) {
    $getCity = Shipment::whereId($shipment->shipment_id)->with(['receiver.city'])->first();
    $cities[] = $getCity->receiver->city;
}
$groupedCities = collect($cities)->groupBy('id');

In this example, we first retrieve the cities as before, but instead of just adding the city name to the $cities array, we add the entire City model object. Then, we use the collect function to convert the $cities array into a collection, and call the groupBy method on it, passing in the id attribute as the grouping key.

This will return a new collection where each item is a group of cities with the same ID. You can then loop through this collection to display the results as needed.

tisuchi's avatar

@johnef_sh Does it work?

$getShipments = PickupList::whereUniqueId($uniqueId)->get(['shipment_id']);

$cities = [];
foreach ($getShipments as $shipment) {
    $getCity = Shipment::whereId($shipment->shipment_id)->with(['receiver.city'])->first();
    $cityName = $getCity->receiver->city->name;
    $cityId = $getCity->receiver->city->id;
    
    $cities[$cityId][] = $cityName;
}


// Get all cities grouping by

johnef_sh's avatar
johnef_sh
OP
Best Answer
Level 2

I have made it in different way in fact

Here is how one of my friends suggest

$getShipments = PickupList::whereUniqueId($uniqueId)->get(['shipment_id']);

        $getCity = Shipment::whereIn('id', $getShipments->pluck('shipment_id'))->with(['receiver.city'])->get();
        return $getCity->mapWithKeys(function ($item) {
            return [$item->receiver->city->id => $item->receiver->city->name];
        });

And it gives just the exact results I need.

Please or to participate in this conversation.