I'm trying to create a page which basically pulls video streams and organises them by viewer count so the one with the most views is at the top of the page.
I'm fairly new to PHP so the way I've done it is extremely inefficient and long but the main thing to know is I use nested switches.
This works perfectly when every video has a different number of viewers above 0. My problem comes when 2 videos have the same amount of viewers. When this happens all streams retain their original order.
Here is a stripped down version of the piece of code causing the problem.
$viewarray = array($viewers1, $viewers2, $viewers3, $viewers4);
rsort($viewarray, SORT_NUMERIC);
for ($z=0; $z<=3; $z++)
{
if ($viewarray[$z] == 0) {break;}
switch($viewarray[$z])
{
case $viewers1:
switch($z)
{
case 0:
//code which implements the re-ordering
case 1:
case 2:
case 3:
}
break;
case $viewers2:
switch($z)
{
case 0:
case 1:
case 2:
case 3:
}
break;
case $viewers3:
switch($z)
{
case 0:
case 1:
case 2:
case 3:
}
break;
case $viewers4:
switch($z)
{
case 0:
case 1:
case 2:
case 3:
}
break;
}
}
$viewarray
is sorted so that it creates a list of the viewer numbers in correct order. The switch then checks each of these numbers against the actual number of viewers for each stream to find the one it matches.
I thought if a switch argument matched 2 cases it would just pick the first one but sadly not. I have tried replacing it with if statements as well but the same thing happens.
Any help would be appreciated.
whoa whoa whoa. scrap this entire thing. what you should be doing is something more like, each stream should have a database record. whenever someone views the stream, a column in the database record should be incremented as a view counter. you then add an index to this column in your database table, and when you pull the streams from your database to list them, you simply sort by the number of views column in your SQL query. ORDER BY viewCounter
EDIT: Only do this if you can't fetch the videos in the right order!
Why not do an associated array like this: array($video2 => $viewers1, $video2 => $viewers2)
then you can sort by the values. You can then use arsort() and just read the video keys from the array to deal with the re-ordering.