Jump to content

associative arrays from database


AdRock

Recommended Posts

Just looking for some advice on how to do this.  I can probably code it if someone tells me the best way to do this

 

I want to connect to the database and from one field in the database (e.g. colours) I want to get all possible values and count how many times each value occurs.

 

I then want to create an associative array with each vale and how many times that value occured e.g.

 

Red => 10

Yellow => 5

Green => 3

Blue => 7

 

I know I can create an array of the colours (or whatever i want) and I know I can comibe the arrays but how would I get each value to increment?

 

Would I use a switch statement inside the while loop from query that checks the value and increments the variable assingned to the value each time it occurs

 

while ($row = mysql_fetch_array($result) {
    switch($row['field']) {
         case 'red':
                $red++;
                 break;
         case 'yellow':
                $yellow++;
                 break;
         case 'green':
                $green++;
                 break;
         case 'blue':
                $blue++;
                 break;
         default:
    }
}

 

If i do it that way how do i get all those variables into an array so i can comibne the 2 arrays?

 

Any help or advice appreciated

 

Link to comment
Share on other sites

$colours = array();
while ($row = mysql_fetch_array($result) {
    if (isset($colours[$row['field']])) {
         $colours[$row['field']]++;
    } else{
         $colours[$row['field']] = 1;
    }
}
print_r($colours);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.