Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

eggplantSword's avatar

Format collection

I'm trying to filter a collection of question answers and I want to get the total answers per answer if that makes sense, for example: a yes or no question, I want to know how many people said yes and how many people said no.

Right now I'm grouping by the answer but after that I'm lost on how I can format the collection to be simpler to read.

Right now its like this, as you can see it's messy and I think I would rather have it simply be 'answer' => '3', 'total' => 2 (this is for an excel export so all this info is not necessary)

Illuminate\Support\Collection {#549 ▼
  #items: array:2 [▼
    3 => Illuminate\Database\Eloquent\Collection {#580 ▼
      #items: array:1 [▼
        0 => App\Models\SurveyAnswer {#614 ▼
          #connection: "mysql"
          #table: "survey_answers"
          #primaryKey: "id"
          #keyType: "int"
          +incrementing: true
          #with: []
          #withCount: []
          #perPage: 15
          +exists: true
          +wasRecentlyCreated: false
          #attributes: array:7 [▶]
          #original: array:7 [▶]
          #changes: []
          #casts: []
          #dates: []
          #dateFormat: null
          #appends: []
          #dispatchesEvents: []
          #observables: []
          #relations: []
          #touches: []
          +timestamps: true
          #hidden: []
          #visible: []
          #fillable: []
          #guarded: array:1 [▶]
        }
      ]
    }
    2 => Illuminate\Database\Eloquent\Collection {#564 ▼
      #items: array:1 [▶]
    }
  ]
}

This is the code

$answers = collect($question['answerPager']->groupBy('answer'));

How can I manipulate this so make it simpler?

0 likes
1 reply
deepu07's avatar

@msslgomez

$answers = collect($question['answerPager']->groupBy('answer'))->toArray();

after you can write foreach loop for looping

Please or to participate in this conversation.