php sort help required please :)

Discussion in 'Web Design and Development' started by CavemanUK, Feb 13, 2011.

  1. CavemanUK macrumors 6502

    CavemanUK

    Joined:
    Jun 29, 2006
    Location:
    Rhyl, North Wales
    #1
    Hi,

    i hope i can explain this correctly.. I am making a page that creates a 3d pie chart for the different types of calls my work has. I have a MySQL database that has jobs and referrers.. Anyway thats not imporant.. what I need to pass to the pie chart is the top 10 best referrals. The two bits of data for each record i have are...

    $referrer[] (pulled from a Jobs table in my database)
    $referrercount[] (a count of all jobs for that referrer query)..

    I know php has a sort feature but i need the 2 variables to stay in sync. I know i need to use a 2 dimensional array but I really am struggling to understand them. can someone give me a code example using the following data...

    $referrer[0] = "Company A"
    $referrercount [0] = 300

    $referrer[1] = "Company B"
    $referrercount [1] = 500

    $referrer[2] = "Company C"
    $referrercount [2] = 100




    I hope this makes sense..?
     
  2. elppa macrumors 68040

    elppa

    Joined:
    Nov 26, 2003
    #2
    See: http://www.php.net/manual/en/array.sorting.php
    PHP:
    <?php
        $referrer
    [0] = "Company A";
        
    $referrercount[0] = 300;

        
    $referrer[1] = "Company B";
        
    $referrercount[1] = 500;

        
    $referrer[2] = "Company C";
        
    $referrercount[2] = 100;
        
        
    // sort high to low, maintain indices
        
    arsort($referrercount);
        foreach(
    $referrercount as $key => $value) {
            echo 
    "{$referrer[$key]}{$referrercount[$key]}".PHP_EOL;
        }
    ?>

    Prints:
    Code:
    Company B: 500
    Company A: 300
    Company C: 100
    Hope I have understood and that is what you are after? :)
     
  3. Darth.Titan macrumors 68030

    Darth.Titan

    Joined:
    Oct 31, 2007
    Location:
    Austin, TX
    #3
    Sounds to me like you'd be better off doing your sorting in your sql query and only pulling the relevant results with something like:
    Code:
    ...
    ORDER BY COUNT(referrer) DESC
    LIMIT 10
    Not knowing your table schema that's about as specific as I can get.
     
  4. CavemanUK thread starter macrumors 6502

    CavemanUK

    Joined:
    Jun 29, 2006
    Location:
    Rhyl, North Wales
    #4
    Thanks guys for your replies.. going to try the code suggestion now... i cant do it with a query as one of the variables is the result of a record count rather than a field itself...
     
  5. CavemanUK thread starter macrumors 6502

    CavemanUK

    Joined:
    Jun 29, 2006
    Location:
    Rhyl, North Wales
    #5
    elppa's suggestion worked a treat. thanks guys.
     

Share This Page