1

I have an array like:

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
        )

    [2] => Array
        (
            [0] => d
            [1] => e
            [2] => f
        )

)

I want to convert my array to a string like below:

$arrtostr = 'a,b,c,d,e,f';

I've used implode() function but it looks like it doesn't work on two-dimensional arrays.

What should I do?

1

3 Answers 3

4

Alternatively, you could use a container for that first, merge the contents, and in the end of having a flat one, then use implode():

$letters = array();
foreach ($array as $value) {
    $letters = array_merge($letters, $value);
}

echo implode(', ', $letters);

Sample Output

Sign up to request clarification or add additional context in comments.

Comments

1

Given your subject array:

$subject = array(
    array('a', 'b'),
    array('c'),
    array('d', 'e', 'f'),
);

Two easy ways to get a "flattened" array are:

PHP 5.6.0 and above using the splat operator:

$flat = array_merge(...$subject);

Lower than PHP 5.6.0 using call_user_func_array():

$flat = call_user_func_array('array_merge', $subject);

Both of these give an array like:

$flat = array('a', 'b', 'c', 'd', 'e', 'f');

Then to get your string, just implode:

$string = implode(',', $flat);

Comments

1

You asked for a two-dimensional array, here's a function that will work for multidimensional array.

function implode_r($g, $p) {
    return is_array($p) ?
           implode($g, array_map(__FUNCTION__, array_fill(0, count($p), $g), $p)) : 
           $p;
}

I can flatten an array structure like so:

$multidimensional_array = array(
    'This',
    array(
        'is',
        array(
            'a',
            'test'
        ),
        array(
            'for',
            'multidimensional',
            array(
                'array'
            )
        )
    )
);

echo implode_r(',', $multidimensional_array);

The results is:

This,is,a,test,for, multidimensional,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.