Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I "dual" implode a nested array?

I have a nested array (only one level deep) like this:

$a = array(
  array( 1, 2, 3 ),
  array( 2, 4, 6 ),
  array( 5, 10, 15 )
  );

And I'd like a nice way to implode() it to this form:

1,2,3|2,4,6|5,10,15

I can run a loop to implode(',',...) each array in $a (storing those strings in a temp), and then implode('|',...) that temporary array, but it seems like I should be able to do this more concisely* with PHP.

Thanks in advance,
Cheers!

*By "more concisely" I mean, without writing a loop (so, just using function calls)

like image 640
Chris Tonkinson Avatar asked May 21 '10 13:05

Chris Tonkinson


3 Answers

I'm late to the game here (by SO standards) but you could literally "dual" implode.

implode('|', array_map('implode', array_fill(0, count($a), ','), $a))
like image 91
salathe Avatar answered Oct 18 '22 21:10

salathe


function implodeComas($arr)
{
    return implode(',',$arr);
}
$out = implode('|', array_map('implodeComas', $a));

echo $out;

Better one:

function myImplode($ret,$current)
{
    if($ret)
        $ret .= '|';

    return $ret .= implode(',',$current);
}

echo array_reduce($a, 'myImplode');
like image 33
dev-null-dweller Avatar answered Oct 18 '22 21:10

dev-null-dweller


Here is a really dirty way:

str_replace('],[', '|', trim(json_encode($a), '[]'));
like image 5
Tom Haigh Avatar answered Oct 18 '22 21:10

Tom Haigh