Jump to content

[SOLVED] extracting data from array


zipperhead

Recommended Posts

Hello, I'm hoping someone can help me with this...I have a query which counts the number of locations per category and outputs the results into an array. What I am trying to do is extract the COUNT value out of the array and save it to a variable based on location.

 

The query looks like this:

$query = "SELECT location, COUNT(*), category FROM table1 
          WHERE category='football' GROUP BY location"; 

 

Outputting the results using the statement below appears to give the correct answers.

 
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
    echo $row['COUNT(*)'] ." ". $row['location'];
    echo "<br />";
}?>

 

Results:

3 California

6 Colorado

1 Florida

etc...

 

What I am trying to do is extract out the results (the COUNT value) based on location from the array into variables to use in other places. I know the code below is wrong but I hope it at least shows the intent.

 

$cal=$row['COUNT(*)'] while ($row['location'] ='California');

$col=$row['COUNT(*)'] while ($row['location'] ='Colorado');

$flo=$row['COUNT(*)'] while ($row['location'] ='Florida');

 

Then can display the variables in other places as needed.

 

echo $cal;

 

results in: "3"

 

I hope this makes sense as I am quite new to this stuff. So far nothing I have tried seems to work, Any suggestions on how to do this would be most helpful. Maybe using something besides the "fetch_array" would work better?

 

thanks a bunch, ZH

 

 

Link to comment
Share on other sites

I recommend making an array (lets call it $arr) where the index is $row['location'] and the value is $row['COUNT(*)']. You can then reference the value using $arr['California']

 

$arr = array();
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
    $arr[$row['location']] = $row['COUNT(*)'];
}

echo $arr['California']; // will output 3

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.