-1

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?

Keith D Kaiser
  • 1,016
  • 2
  • 14
  • 31
  • 5
    Mysql is way better at it `SELECT DISTINCT name FROM table;` – Sammitch Jul 20 '21 at 19:51
  • or if you want to keep doing it in PHP, add the names to the array in the loop and call `array_unique()` _after_ the loop. Right now you're basically doing `array_unique('Bill');` and overwriting the array entirely instead of appending, which would be `$collecting_names[] = ...`. – Sammitch Jul 20 '21 at 19:53

2 Answers2

1

Array_unique is applied after you've finished building the 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];
}
Kinglish
  • 23,358
  • 3
  • 22
  • 43
0

$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);
Barmar
  • 741,623
  • 53
  • 500
  • 612