Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplify a multidimensional array to a string [duplicate]

Tags:

arrays

php

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.

like image 645
mzcoxfde Avatar asked Jul 18 '26 16:07

mzcoxfde


2 Answers

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"
like image 119
Robin Panta Avatar answered Jul 20 '26 06:07

Robin Panta


A simple and obvious solution might be:

$res = "";
for ($i = 0; $i < count($tag); $i++) {
    $res .= $tag[$i]["tag_name"] . ",";
}
$res = trim($res, ","); //Removing the extra commas
echo $res;

You basically iterate through the array, and every element you iterate through, you add it's tag_name to a $res string.

like image 36
Yotam Salmon Avatar answered Jul 20 '26 06:07

Yotam Salmon