Lozza's avatar
Level 4

Convert result to indexed array

I am trying to sum data into an indexed array.

I have this code:

$sa=App\Models\SeatAllocation::where('seat_id','<',65800)->groupBy('seat_id')->selectRaw('count(*) as total, seat_id')->get()->map
->toArray()    

Which returns this data:

[
      [
        "total" => 6,
        "seat_id" => 65798,
      ],
      [
        "total" => 6,
        "seat_id" => 65799,
      ],
]

But I would like to result in an indexed array like this:

[
	65798 => 6,
	65799 => 6
]

Is this possible?

Any help gratefully received!! :)

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

Certainly! You can achieve the desired indexed array by using the pluck method with the keyBy method. Here's how you can modify your code:

$sa = App\Models\SeatAllocation::where('seat_id', '<', 65800)
    ->groupBy('seat_id')
    ->selectRaw('count(*) as total, seat_id')
    ->get()
    ->pluck('total', 'seat_id')
    ->toArray();

The pluck method retrieves all of the values for a given key (in this case, 'total'), and the second argument to pluck specifies the key for the resulting array (in this case, 'seat_id'). The toArray method then converts the collection to a plain PHP array.

The resulting $sa array will have the seat_id as the key and the total as the value, just as you wanted:

[
    65798 => 6,
    65799 => 6
]
Lozza's avatar
Level 4

Great answer, thanks Mr AI!! Turns out I don't even need the toArray() as the pluck already achieves this!!

Please or to participate in this conversation.