How to sort array by something in php? -
this question has answer here:
- sort array of objects object fields 12 answers
i have data this
array([0] => stdclass object ( [id] => 1 [title] => aaaa [sentence] => abcdefgh [rank] => 3 ) [1] => stdclass object ( [id] => 2 [title] => bbbb [sentence] => ijklmn [rank] => 1 ) [3] => stdclass object ( [id] => 3 [title] => ccc [sentence] => opqrstu [rank] => 2 ));
show data:
foreach($data $d) { $title = $d->title; $sentence = $d->sentence; $rank = $d->rank; echo $title. " | " .$sentence. " | " .$rank. "<br>"; }
how sort 'rank'? help.
you can use php's usort
function uses objects' attribute rank
criteria:
function rank_compare($a, $b) { return $a->rank - $b->rank; } usort($data, 'rank_compare');
Comments
Post a Comment