Dr-Zee
Dr-Zee

Reputation: 113

Using keys in a php array to sort and change div display order

I have an array of dynamic php variables that are keys to several div id's. I'm looking for a way to sort the php quantities and use that sequence to re-order my divs. I have found a few threads on how to use jquery to re-order divs based on an array input, but they're all just different enough that with my skill level, I haven't been able to adapt they're suggestions effectively. Here is a thread that is very close to what I'm trying to do. Dynamically arranging divs using jQuery

A clear explanation of my goal: contestants raise money, each has a fundraising page. The php variable is the amount of money they've raised pulled from their page. The function will order the divs on the page to show the top earner first, and so on.

The code below reflects my layout, however I should clarify that my divs all have unique content, so dynamic generation won't work for them.

<?php 

$Contestants = array(
    $Totals[0] => 'contestant0', 
    $Totals[1] => 'contestant1',
    $Totals[2] => 'contestant2'
);

krsort ($Contestants);

?>

<div id="container">
 <div id="contestant0">
  <p><?php print ($Totals[0]) ?></p> 
 </div>
 <div id="contestant1">
  <p><?php print ($Totals[1]) ?></p> 
 </div>
 <div id="contestant2">
  <p><?php print ($Totals[2]) ?></p> 
 </div>
</div>

I know how barebones the code I've given is, but the javascript I've pounded out I believe is pretty useless and at best embarrassing.

Any help is hugely appreciated.

Upvotes: 2

Views: 2130

Answers (2)

Doug Avery
Doug Avery

Reputation: 1057

Made a quick example over at JSfiddle:

http://jsfiddle.net/2U7fv/4/

It sounds like you need to use a standard JS method, "sort()", which takes a two argument method that compares both arguments, and returns a value of 1 or more if argument B should be sorted before than argument A. http://www.w3schools.com/jsref/jsref_sort.asp

So the process is:

  • Put all your divs in an array
  • Run than array through a sorting method
    • The sorting method:
    • Gets the donation amounts of two divs
    • Parses off the dollar sign
    • Returns 1 or more if B is higher, 0 or less if A is higher
  • This returns a sorted array of DOM nodes
  • Convert that array to one long HTML string
  • Set the #container html to that string

Upvotes: 0

aziz punjani
aziz punjani

Reputation: 25796

No jQuery needed, unless i'm missing something.

<?php 

$Contestants = array(
    $Totals[0] => 'contestant0', 
    $Totals[1] => 'contestant1',
    $Totals[2] => 'contestant2'
);

rsort ($Contestants);

?>


<div id="container">
<?php foreach( $Contestants as $k => $v ) { ?>  
   <div id="<?php echo $v ?>">
     <p><?php echo $k ?></p> 
    </div>
<?php } ?>
</div> 

Upvotes: 1

Related Questions