mzcoxfde mzcoxfde - 4 months ago 18
PHP Question

Simplify a multidimensional array to a string

I have this kind of array in my

$tag
variable.

Array
(
[0] => Array
(
[tag_name] => tag-1
)
[1] => Array
(
[tag_name] => tag-2
)
[2] => Array
(
[tag_name] => tag-3
)
)


What I'm trying to do is get all the tag names and implode them with a coma then make it a value for a text input field.

I've tried for and foreach loops so many different ways but with not much success. I'm using CodeIgniter if that helps.

Thanks in advance.

Answer

You can use array_column followed by join or implode

Try this :

$string = join(',', array_column($array, 'tag_name'));

Explanation:

array_column returns the values from a single column from the input array

For your array, array_column($array 'tag_name') returns an array containing values of index tag_name, i.e returned array would be :

Array
(
    [0] => tag-1
    [1] => tag-2
    [2] => tag-3
)

Joining with join or implode , you get your desired string,

//$string = "tag-1,tag-2,tag-3"