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

Flip87's avatar

Sort Objekt in PHP by a key value

I need to sort the Ojekt $notes by the "hits" value in a PHP script, how can I do?


$notes = Note::whereIn('id' , $idArray)->get();

if(!empty($keywordArray)) { foreach($keywordArray as $keyword) { foreach($notes as $note) { if($note->name != $this->keywordHighlighting($keyword, $note->name) or $note->description != $this->keywordHighlighting($keyword, $note->description)) { $note->name = $this->keywordHighlighting($keyword, $note->name); $note->description = $this->keywordHighlighting($keyword, $note->description); $note->hits++; } } } }

return view('notes.show')->with('notes', $notes);

0 likes
1 reply
Flip87's avatar
Flip87
OP
Best Answer
Level 1

sort it by using Collections Methodes

//sort it by value $notes = $notes->sortBy('hits');

//reverse the sequence $notes = $notes->reverse();

1 like

Please or to participate in this conversation.