简体   繁体   中英

Echo Array Values in Comma Separated List

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM