arrays - PHP Iterator Custom Sort Order (Laravel 4) -
i have "post" object, accessed via ioc container. various errors tell me object's type ends "collection", implements several interfaces, including iteratoraggregate , arrayaccess.
i want display user-defined group of posts according specific order, e.g.:
$desired=array("69","63","70");//these represent post id's
just sorting array in manner seems complex, want sort collection. have been researching various combinations of usort(), uksort(), eloquent's sortby(), array_multisort()... obvious solutions result in orders 3,2,1 or 1,2,3, not 2,1,3.
the closest have gotten goal fetch ones want,
//blogcontroller private function myposts($desired){ $posts=$this->post->wherein('id',$desired)->get(); ...
"convert" collection object array,
$posts=$posts->toarray();
and treat array custom function: source
function sortarraybyarray($array,$orderarray) { $ordered = array(); foreach($orderarray $key) { if(array_key_exists($key,$array)) { $ordered[$key] = $array[$key]; unset($array[$key]); } } return $ordered + $array; } $sorted=sortarraybyarray($array1,$desired);
i can vardump array in correct order, since array, can't access $posts object in view. can convert array post object?
this whole approach feels wasteful anyway, converting array , back... it? there more straightforward way of sorting contents of "collection"?
this little better, perhaps (a native php function):
array_multisort($desired,$posts,sort_string); //only works string keys //$desire=(1,2,3) not work!
again, works arrays, attempting directly on "posts" object fails...
finally, discovered using presenter: https://github.com/robclancy/presenter#array-usage works in view, after 1 of above completed in controller:
@foreach($posts $post) <?php $post=new postpresenter($post) ?> {{view::make('site.post.article')->with(compact('post'))}} @endforeach
this works, still feels long way it. there better way accomplish task? performance concerns or best practices 1 method vs. another? in advance able help.
you can use collections own sort method , pass in callback. callback compares every 2 values in collection tells sort method 1 "higher". sort method sorts them accordingly. if want specific value order create mapping , sort that. more info check uasort
$posts->sort(function($a, $b){ $desired=array("69" => 0,"63" => 1,"70" =>2); if(!array_key_exists($a,$desired) || !array_key_exists($b,$desired) || $a == $b){ return 0 } else{ return ($desired[$a] < $desired[$b]) ? -1 : 1; } });
Comments
Post a Comment