-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?

2
  • 5
    Mysql is way better at it SELECT DISTINCT name FROM table; Commented Jul 20, 2021 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[] = .... Commented Jul 20, 2021 at 19:53

2 Answers 2

1

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];
}
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.