KeepCool KeepCool - 1 month ago 8
PHP Question

Implode multi-dimensional array with different delimiters?

I'm looking to implode my array into a string that looks like this:

1,a,v,v|2,b,v,v|3,c,v,v|4,d,v,v|5,d,v,v

Here's my array:

array (size=5)
0 =>
array (size=4)
0 => string '1' (length=1)
1 => string 'a' (length=1)
2 => string 'v' (length=1)
3 => string 'v' (length=1)
1 =>
array (size=4)
0 => string '2' (length=1)
1 => string 'b' (length=1)
2 => string 'v' (length=1)
3 => string 'v' (length=1)
2 =>
array (size=4)
0 => string '3' (length=1)
1 => string 'c' (length=1)
2 => string 'v' (length=1)
3 => string 'v' (length=1)
3 =>
array (size=4)
0 => string '4' (length=1)
1 => string 'd' (length=1)
2 => string 'v' (length=1)
3 => string 'v' (length=1)
4 =>
array (size=4)
0 => string '5' (length=1)
1 => string 'd' (length=1)
2 => string 'v' (length=1)
3 => string 'v' (length=1)


Any help would be greatly appreciated.

Thanks.

Answer

If you were starting with an array of strings, like this:

$strings = ['1,a,v,v', '2,b,v,v', '3,c,v,v', '4,d,v,v', '5,d,v,v'];

It would be easy:

$result = implode('|', $strings);

You probably already know how to do that. So the question is how to get this array of arrays

$arrays = [
    ['1','a','v','v'],
    ['2','b','v','v'],
    ['3','c','v','v'],
    ['4','d','v','v'],
    ['5','d','v','v']
];

into the same format as $strings.

Fortunately that's easy too. Just do the same thing, only in a loop.

foreach ($arrays as $array) {
    // implode each item and add the result to a new array
    $strings[] = implode(',', $array);
}

It can also be done using the array_map function.

$strings = array_map(function($array) {
    return implode(',', $array);
}, $arrays);

For something basic like this, it really doesn't matter which way you do it.