Context: I’m querying a database to return a specified number of monsters to be used in a fight within a simple web based RPG.
Problem: I have a straightforward MYSQL query that includes a WHERE clause to determine the “level” of the monsters. In a previous function I’m building an array that includes the levels of the corresponding monsters that should be returned; something like:
$levels = Array( [0] => 3 [1] => 1 [2] => 1 )
So in the above array, the Value corresponds to the level. So I’m looking to return 3 monsters — Level 3, Level 1 and Level 1.
Simple enough. Now I want to query MYSQL with the following and presumably use a loop to do the query 3 times to get my 3 monsters; something like:
$query = "SELECT *, CardHP as EncounterCardHP, CardAP as EncounterCardAP";
$query .= " FROM Cards";
$query .= " WHERE CardTypeId = 1 AND CardRarity = {$level}";
$query .= " ORDER BY RAND() LIMIT 1";
So in the above query, the variable {$level} is the Monster Level from the previous array. The loop formatting is where I’m struggling. I’m trying something like:
while ($i = $levels) {
$query = "SELECT *, CardHP as EncounterCardHP, CardAP as EncounterCardAP";
$query .= " FROM Cards";
$query .= " WHERE CardTypeId = 1 AND CardRarity = {$i}";
$query .= " ORDER BY RAND() LIMIT 1";
$result_set = mysql_query($query, $connection);
confirm_query($result_set);
return $result_set;
}
I think this is close, but I’m not seeing how I can get this to ultimately give me a single array of monsters from MYSQL. It seems in the above, I’m building 3 separate arrays? Do I need to use array_merge(), or is there a simpler more elegant way to do this? If I were getting all the same level monsters I could simply just run the query 1 time and LIMIT 3, but I need monsters to correspond to what the previous array shows.
Making sense? Help is always appreciated.
It was actually much easier than I thought; maybe I over-explained the issue. Here is what I did.
1) Once I returned my array $levels which looked like this:
2) I created an empty array called $result_set
2) Then looped through the $levels array with a foreach loop and ran the query with the first $level in the $levels array. However, rather than just returning the $result_set with the first row returned, I inserted the first row into the empty array I created in step 2. After each loop through, I inserted the new row from MYSQL into the now filled $result_set array.
Here is what it looked like in the end:
My $result_set now has 3 monsters in it, a level 3, level 1 and level 2, all chosen randomly from the database for each respective level.
Thanks for all the help.