Filter elements of a collection in Laravel

Viewed 36

I have the following elements collection and I want to save in a new array only the first elements whose "question_id" field are different from each other. I mean, only the elements with "id" 11 and 12 that have the "question_id" field different, would be saved and the other elements would not be saved in the new array, how could I do it in Laravel?

dump of entities with unique id attributes and just two distinct question_ids

2 Answers

Use the key of the array.

$qid[$id] = 1;

$collection->unique('question_id')->values() will get you the desired result.

$array = [
  [
    "id"=> 11,
    "question_id"=> 22,
    "answer Id"=> 72
  ],
  [
    "Id"=> 12,
    "question_id"=> 23,
    "answer_1d"=> 76
  ],
  [
    "id"=> 13,
    "question_id"=> 23,
    "answer_id"=> 77
  ],
  [
    "id"=> 14,
    "question_id"=> 22,
    "answer_id"=> 77
  ]
];

For this dataset

dd(collect($array)->unique('question_id')->values());

will return

#items: array:2 [▼
    0 => array:3 [▼
      "id" => 11
      "question_id" => 22
      "answer Id" => 72
    ]
    1 => array:3 [▼
      "Id" => 12
      "question_id" => 23
      "answer_1d" => 76
    ]
  ]
Related