0

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?

4 Answers 4

4

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

Comments

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

1 Comment

Jeremy Blalock's answer is cleaner :-)
0

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

2 Comments

Sorry, maybe I should've added in the question that the size of the array is indeed dynamic like Michael mentioned. Any suggestions?
I have edit :), try now, now he can also remove the random -1
0

Use something like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.