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
https://forums.phpfreaks.com/topic/122297-solved-extracting-data-from-array/
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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.