Question

Just been looking at some examples involving usort and I cant quite get my head around making the function for my array. Im sure it is quite simple, so I thought I would ask on here. I am using twig and redbean but I dont think that is relavant. Here is my code:

$user = $_SESSION['user'];
$userfol =  R::find('follow','user_id=?', array($user->id));
foreach ($userfol as $uf)
{
    $userrec = R::find('recipe','user_id=?', array($uf->following_id));
}

I want to SORT the array $userrec to display recipes by their date created and I want to limit it to displaying only 1 recipe at a time. Any Ideas?

Thanks very much in advanced.

Was it helpful?

Solution

Like stated in the comments doing this in the database would be the most efficient. Looking up the documentation for RedBean I found http://redbeanphp.com/manual2_0/finding_beans. Taking from there:

$needles = R::find('needle',' haystack = :haystackname 
                              ORDER BY :sortorder', 
array( 'sortorder'=>$sortorder, ':haystack'=>$haystack ));

Applying this example to your code above would be done as follows:

$user = $_SESSION['user'];
$userfol =  R::find('follow','user_id=? ORDER BY create_date', array($user->id));
foreach ($userfol as $uf)
{
    $userrec = R::find('recipe','user_id=?', array($uf->following_id));
}

The above example's sort order is not dynamic, but you can replace it with a question mark just like the user id.

While I'm at it, you can use :name instead of question marks. Question marks are evaluated in the order you put them there, and take the values from the data array in order. When started with a colon it will look for that name in an associative array, which may be favorable.

If for some reason you want to use usort anyway, I set up an example here. As you can see the sorter function compares the create_date element of $a and $b, you can replace this with something relevant to your application. As for what you should return, to quote from the docs:

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top