How do I use array_unique() with the output of MySQL query

704 Views Asked by At

I have a fairly complex MySQL call that results in simple output something like this;

name  timestamp             comm1 comm2 counter
Bill  2021-04-18 19:31:00   data  data  1
Bill  2021-04-18 19:32:00   data  data  2
Bill  2021-04-18 19:33:00   data  data  3
Bill  2021-04-18 19:34:00   data  data  4
Tom   2021-04-18 19:31:00   data  data  1
Tom   2021-04-18 19:35:00   data  data  2
Tom   2021-04-18 19:37:00   data  data  3
Tom   2021-04-18 19:38:00   data  data  4

... and many more rows.

Using PHP I want to create an array of just the unique values of the name. So in this case Bill and Tom. I thought I would use foreach to put each of the 8 names in an array and then use array_unique to bring it down to just the two. But I'm not clear on how to do that, as simple as it sounds and after various attempts have not got it working.

$collecting_names = array();
foreach($db_found->query($sql) as $cnrow) {
   $collecting_stations = array_unique($cnrow[name]);
}

What am I doing wrong?

2

There are 2 best solutions below

0
Kinglish On BEST ANSWER

Array_unique is applied after you've finished building the array. Array_unique removes duplicate values from an array.

$collecting_names = array();
foreach($db_found->query($sql) as $cnrow) {
   $collecting_names[] = $cnrow[name];
}
$collecting_names = array_unique($collecting_names);

You could alternatively check if it exists before adding it.

$collecting_names = array();
foreach($db_found->query($sql) as $cnrow) {
   if (!in_array($cnrow[name], $collecting_names))  $collecting_names[] = $cnrow[name];
}
0
Barmar On

$cnrow['name'] is not an array, it makes no sense to call array_unique() there.

You call array_unique() on the array of results after the loop is done.

$collecting_names = array();
foreach($db_found->query($sql) as $cnrow) {
   $collecting_names[] = $cnrow['name'];
}
$collecting_names = array_unique($collecting_names);