php - Ranking values in array -
i have running in while loop add array every time goes through it. however, issue trying assign ranks each value. saw horse1
had ap=51
, ep=47
, sp= 32
, fx=20
. horse2
had ap=52
, ep = 55
, sp=30
, f=19
. trying make print on screen so:
ap ep sp fx horse 1 2 2 1 1 horse 2 1 1 2 2
and etc many horses there are.
here code have. not versed in php thought way go.
$allstats[]= array ( "ap"=>"x".$ap, "ep"=>"x".$ep, "sp"=>"x".$sp, "fx"=>"x".$fx, "horse"=>$horse, ); $apranks[$ap]; $epranks[$ep]; $spranks[$sp]; $fxranks[$fx]; ksort($apranks,2); ksort($epranks,2); ksort($spranks,2); ksort($fxranks,2); $finalap=(array_keys($apranks,$ap)); ?> <div id="rankings"> <? echo array_search($ap,$finalap);?><? echo array_search($ep,$epranks);?><? echo array_search($sp,$spranks);?><? echo array_search($fx,$fxranks);?> </div>
assuming horse array this,
$horses[1]=array('ap'=>51,'ep'=>47,'sp'=>32,'fx'=>20); $horses[2]=array('ap'=>52,'ep'=>55,'sp'=>30,'fx'=>19); $horse_values = array('ap','ep','sp','fx'); $horse_rank = array(); foreach($horse_values $k=>$val) { uasort($horses, create_function('$a, $b', 'return custom_sort($a, $b, "'.$val.'");')); $i=1; foreach($horses $l=>$horse) { $horse_rank[$l][$val] = $i; $i++; } } function custom_sort( $a, $b, $meta ) { if ( $a[$meta] == $b[$meta] ) return 0; else if ( $a[$meta] > $b[$meta] ) return -1; else return 1; //echo "$a, $b, $meta<hr>"; // debugging output } arsort($horse_rank); //sorting final rank array based on horse number print_r($horse_rank);
output:
array ( [1] => array ( [ap] => 2 [ep] => 2 [sp] => 1 [fx] => 1 ) [2] => array ( [ap] => 1 [ep] => 1 [sp] => 2 [fx] => 2 ) )
Comments
Post a Comment