-1

I am selecting values from my database, when I dump the $results I get;

array (
  0 => 
  (object) array(
     'FieldName' => 'certification_name',
     'FieldValue' => 'White Belt',
  ),
  1 => 
  (object) array(
     'FieldName' => 'certification_name',
     'FieldValue' => 'Yellow Belt',
  ),
)

I want to display the following on my page;

Certification List: White Belt, Yellow Belt

I have created a loop but when I echo the result I get this;

Certification List: Array Array

My PHP code;

foreach ($results as $result) {

    $name = $result->FieldName;
    $value = $result->FieldValue;

    $items[] = array(
        'name' => $name, 
        'value' => $value
    );
}

$items = implode("\n", $items);
echo 'Certification List: ' .$items;

What do I need to change in order to get this working?

jonboy
  • 2,729
  • 6
  • 37
  • 77
  • Can't you do it by just using `$items[] = $result->FieldValue;` – Nigel Ren Feb 24 '20 at 16:54
  • If you don't do anything else with the data, you could also look into the MySQL [`GROUP_CONCAT()`](https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_group-concat) so that you don't have to process the result set at all. – Nigel Ren Feb 24 '20 at 16:59
  • Are you using PDO or MySQLi? If it's PDO, you can use the fetch argument `PDO::FETCH_COLUMN` in your [fetchAll()](https://www.php.net/manual/en/pdostatement.fetchall.php) and it will return the values in the way you want it. – M. Eriksson Feb 24 '20 at 17:06

1 Answers1

2

You shouldn't push arrays into $items, just push the values.

foreach ($results as $result) {
    $items[] = $result->FieldValue;
}
$item_list = implode(", ", $items);
echo "Certification List: $item_list";

You can also replace the loop with:

$items = array_column($results, 'FieldValue');
Barmar
  • 741,623
  • 53
  • 500
  • 612