Squrler
Squrler

Reputation: 3514

Joining array values into string

I have a PHP array with multiple objects. I'm trying to join values from a certain key into one string separated by commas. Output from var_dump:

Array
(
    [0] => stdClass Object
        (
            [tag_id] => 111
            [tag_name] => thing 1
            [tag_link] => url_1
        )

    [1] => stdClass Object
        (
            [tag_id] => 663
            [tag_name] => thing 2
            [tag_link] => url_2
        )

)

The string needs to be $string = 'thing 1,thing 2'. I tried using a foreach loop, but I'm completely stuck. Could anyone help out?

Upvotes: 0

Views: 376

Answers (4)

Peinguin
Peinguin

Reputation: 85

Use something like this:

implode(',', array_map(function ($el) {
    return $el->tag_name;
}, $array));

Upvotes: 0

Sam
Sam

Reputation: 2970

Try as this

$string = $array[0]->tag_name.','.$array[1]->tag_name;

For other elements

 $string = '';
 foreach($array as $object) $string.=$object->tag_name.',';
 $string = substr($string,0,-1);

Upvotes: 0

Scott Yang
Scott Yang

Reputation: 2428

$output = '';
foreach($test as $t){
    $output .= $t->tag_name . ',';
}
$output = substr($output, 0, -1);
echo $output;

Upvotes: 0

Jeremy Blalock
Jeremy Blalock

Reputation: 2619

The above answer is a little light, maybe run it as a foreach loop instead.

$names = array();
foreach ($array as $k => $v) {
    $names[] = $v->tag_name;
}
$string = implode(',', $names);

Upvotes: 4

Related Questions