News:

Bored?  Looking to kill some time?  Want to chat with other SMF users?  Join us in IRC chat or Discord

Main Menu

Sorting Original Output

Started by ptmuldoon, April 02, 2010, 02:25:17 PM

Previous topic - Next topic

ptmuldoon

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?

Arantor

Not without writing the sorting routine to do it yourself.
Holder of controversial views, all of which my own.


ptmuldoon

What about the ability to resort the array after the query?

Arantor

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.
Holder of controversial views, all of which my own.


ptmuldoon

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.

Arantor

*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
Holder of controversial views, all of which my own.


SlammedDime

This should work...

usort($context['plyrank'], create_function('$a, $b', 'return $a[\'rank\'] == $b[\'rank\'] ? 0 : ($a[\'rank\'] < $b[\'rank\'] ? -1 : 1));');
SlammedDime
Former Lead Customizer
BitBucket Projects
GeekStorage.com Hosting
                      My Mods
SimpleSEF
Ajax Quick Reply
Sitemap
more...
                     

Advertisement: