BackTrack57
BackTrack57

Reputation: 395

How to group values of columns using PHP MySQL?

I can't find how to group values of 7 MySQL columns.
Columns :

ex_MONDAY
ex_TUESDAY
ex_WEDNESDAY
ex_THURSDAY
ex_FRIDAY
ex_SATURDAY
ex_SUNDAY

Values are more or less the same exemple

15-00035 / 15-00035 / 12-00014 / 11-00004 / 11-00004 / 11-00004 / 11-00004 / 

I would like it group those values and I could use them in a while ($z < mysql_num_rows($result)) and as result I would get something like this:

15-00035
12-00014
11-00004

Because as grouped there is only 3 different values.

Currently i'm using this code but it seems to not work:

$result=mysql_query("SELECT ex_MONDAY,ex_TUESDAY,ex_WEDNESDAY,ex_THURSDAY,ex_FRIDAY,ex_SATURDAY,ex_SUNDAY FROM mytable WHERE week=38 AND year=2015 GROUP BY ex_MONDAY,ex_TUESDAY,ex_WEDNESDAY,ex_THURSDAY,ex_FRIDAY,ex_SATURDAY,ex_SUNDAY");

$fetch=mysql_fetch_row($result);

echo "$fetch[0]"; //returns 15-00035
echo "$fetch[1]"; // returns no value
echo "$fetch[2]"; // returns 11-0004

Upvotes: 2

Views: 73

Answers (1)

syck
syck

Reputation: 3029

Use the PHP functions array_unique() and array_values():

$result=mysql_query("SELECT ex_MONDAY,ex_TUESDAY,ex_WEDNESDAY,ex_THURSDAY,ex_FRIDAY,ex_SATURDAY,ex_SUNDAY FROM mytable WHERE week=38 AND year=2015");
$fetch = array_values(array_unique(mysql_fetch_row($result)));

To weed out empty values, additionally use array_filter():

$fetch = array_values(array_unique(array_filter(mysql_fetch_row($result))));

Upvotes: 1

Related Questions