How can I "dual" implode a nested array?
Asked Answered
H

3

5

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)

Hatbox answered 21/5, 2010 at 13:32 Comment(3)
Is there a reason you want this custom-looking flattened structure? Because JSON and serialized PHP both let you turn a complex data structure into a parse-able string.Kisor
I'm generating URIs for the Google Charts API.Hatbox
Ah. That's a good reason! Have you looked at gChartPhp? code.google.com/p/gchartphpKisor
D
8

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))
Dibromide answered 21/5, 2010 at 18:11 Comment(3)
@Dibromide after this implode i get this type data ...... valueA(1),valueB(1)|valueA(2),valueB(2) and i need to store valueA(1),valueA(2) in one column and valueB(1),valueB(2) in second column is this possibleTrescott
@DanishIqbal don't ask random questions in comments, please.Dibromide
@DanishIqbal it is not part of the question above, even if it is tangentially related. Even if your question were related, don't ask questions in the comments.Dibromide
A
6

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');
Agama answered 21/5, 2010 at 13:35 Comment(1)
Great idea. The only caveat is that it looks like array_reduce() strips elements from the back of the array (reversing the subarrays in the output).Hatbox
R
5

Here is a really dirty way:

str_replace('],[', '|', trim(json_encode($a), '[]'));
Rhodes answered 21/5, 2010 at 14:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.