Simple Machines Community Forum

Customizing SMF => SMF Coding Discussion => Topic started by: ptmuldoon on April 02, 2010, 02:25:17 PM

Title: Sorting Original Output
Post by: ptmuldoon on April 02, 2010, 02:25:17 PM
In a function, I'm running a query to pull some data, and then outputting some of that to a template.  Thus, I have something like this below.


$context['plyrank'][] = array(
    'name' => $row['real_name'],
    'wins' => $row['wins'],
    'losses' => $row['losses'],
'rank' => $row['rank']
);


Now, the $row['rank'] is not part of the query, but rather based on formula of wins, losses, and other variables, thus I'm trying to avoiding adding that long equation into the original query and to use ORDER BY rank.

Is there a way to take the array of $context['plyrank'][]  and sort it based on a specific field?
Title: Re: Sorting Original Output
Post by: Arantor on April 02, 2010, 04:10:00 PM
Not without writing the sorting routine to do it yourself.
Title: Re: Sorting Original Output
Post by: ptmuldoon on April 02, 2010, 07:44:58 PM
What about the ability to resort the array after the query?
Title: Re: Sorting Original Output
Post by: Arantor on April 02, 2010, 07:51:10 PM
Sure, just you'll have to do it manually because you can't sort on an item in a multi-dimensional array.

Something like this, maybe:

$sort_ar = array();
foreach ($context['plyrank'] as $key => $data)
{
  $sort_ar[$key] = $data['rank'];
}

asort($sort_ar);

foreach ($sort_ar as $key => $rank)
{
  // do something with $context['plyrank'][$key] now, it'll be in the right order
}


Hence... doing it in your own code like I said.
Title: Re: Sorting Original Output
Post by: ptmuldoon on April 02, 2010, 08:37:29 PM
Thanks.  Everything I know about php has been self taught.  And I'm just getting back into after 18 months of studying for the CPA exam.   Normally, with that small push you've been giving me, I can learn how to figure things out.

I'll be sitting in a car traveling all weekend, so hoping to sit and experiment while someone else does most of the driving.
Title: Re: Sorting Original Output
Post by: Arantor on April 02, 2010, 08:39:35 PM
*nods* Self teaching can be awesome (it's how I learned) but sometimes it does leave great holes in knowledge that end up seeming stupid after a while; I think I'd been programming in PHP for 3 years before I finally came across the sort functions and had previously been implementing quick sort and bubble sort myself :S
Title: Re: Sorting Original Output
Post by: SlammedDime on April 03, 2010, 04:49:18 AM
This should work...

usort($context['plyrank'], create_function('$a, $b', 'return $a[\'rank\'] == $b[\'rank\'] ? 0 : ($a[\'rank\'] < $b[\'rank\'] ? -1 : 1));');