Reputation: 1513
I have an array of objects, and I want to group by "round_number".
$data = AnswerHistory::select(
'answer_histories.round_number',
'answer_histories.answer_time',
'questions.free_text as question_free_text',
'lkp_answers.name as answer_name',
'paragraphs.free_text as paragraph_free_text',
)
->orderBy('answer_histories.id', 'DESC')
->where('answer_histories.user_id', 1)
->whereNotNull('answer_histories.lkp_answer_id')
->leftJoin('questions','answer_histories.question_id','questions.id')
->leftJoin('lkp_answers','answer_histories.lkp_answer_id','lkp_answers.id')
->leftJoin('paragraphs','answer_histories.paragraph_id','paragraphs.id')
->get()->toArray();
//I tried this, but I get only 1 value for each round_number
$new_array = array();
foreach ($data as $item)
if (!array_key_exists($item['round_number'], $new_array))
$new_array[$item['round_number']] = $item;
This is the output:
Upvotes: 1
Views: 41
Reputation: 499
use this ->get()->groupBy('round_number')->toArray()
instead of this ->get()->toArray();
Upvotes: 2