0

I have a PHP game which uses a MySQL table (history) that keeps track of users and how many times they knew the answer like:

username answer
-------- ------
user1    answer1
user2    answer2
user1    answer3

etc. And I want to use this table to print the best players, so I'm trying to implement an array like

public function getBestPlayers($hrows) /*history_rows*/
{
$ray=array();
$hlen = count($hrows);

for($i=0;$i<$hlen;$i++)
{
    $curnick = $hrows[$i]['knower'];
    $ray[$curnick]; //my attempt to "set" the index
    if($ray[$curnick]!=NULL)
    {
        $ray[$curnick]++;
    }
    else
    {
        $ray[$curnick]=1;
    }
}//for
$ray = sort($ray);
return $ray;
}//getBestPlayers()

so that in the end I have $ray['user1'] = 2 , $ray['user2'] = 1 etc. But this gives error "undefined index: user1". what should I do? thanks in advance..

2
  • You should check whether index is defined via isset() function before you even push a new item Commented Jan 14, 2013 at 0:31
  • thanks. OK, I checked and got zero with isset(). then what? Commented Jan 14, 2013 at 0:37

2 Answers 2

3

You should let MySql do this for you, which will be much faster and much easier:

SELECT username, COUNT(*) AS score FROM tbl GROUP BY username ORDER BY score DESC

This will return a result set of the form

username score
-------- ------
user1    2
user2    1
Sign up to request clarification or add additional context in comments.

3 Comments

thanks, but I don't have scores. I have duplicates of user1, which I want to turn into scores dynamically, but don't want to store in mysql.
@marvin: I know. This query will do this automatically. Did you try to execute it?
OMG, this is great! I didn't know MySQL can do this. Thank you very much, and please forgive me for my ignorance :)
0

You ought to drop the $ray[$curnick]; line, as you can't (and shouldn't) try to declare array indices like that. Furthermore, you might want to replace if($ray[$curnick]!=NULL) by if(isset($ray[$curnick])) which will not try to access the array at that place but will merely check if it is set.

Other than that, your code would work, however, it would probably be a good idea to offload the collection of stats to the database.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.