note 35214 added to function.implode
| From: | dan at danposluns dot com | Date: | Sat, 23 Aug 2003 16:04:11 +0000 |
| Subject: | note 35214 added to function.implode | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-54963@lists.php.net to get a copy of this message | ||
*** MULTI-DIMENSIONAL ARRAY IMPLODE ***
First of all, it should be noted that the function in the previous note is not technically correct,
as it glues the outside of the first piece. This is the problem faced by any function that wants to
construct a set out of an array without the overhead of handling the boundary indexes. It also
doesn't preserve the dimensional architecture.
Use this function when you want to call implode() on a multi-dimensional array and want the
resulting string to preserve the architecture of the different dimensions. For example:
array ( 5, array (2, 4, 6), array (3, 6, 9, array (12)))
would be reduced to:
[ 5, [ 2, 4, 6 ], [ 3, 6, 9, [ 12 ] ] ]
Note that this does not preserve key values. If you need those, you are probably better off using
serialize() and then replacing the tokens with your own symbols using the string functions.
Anyway, here is the code:
function mdImpode($x, $y)
{
$a = (is_array($x)) ? '[ ' . array_reduce($x, 'mdImplode') . ' ]' :
$x;
$b = (is_array($y)) ? '[ ' . array_reduce($y, 'mdImplode') . ' ]' :
$y;
return $a . ', ' . $b;
}
Then to call it, use:
$result = '[ ' . array_reduce($pieces, 'mdImplode') . ' ]';
Note that you have to make manual changes if you want different glue or set symbols. There may be a
more elegant solution, but this should be a good compromise between efficiency and simplicity (the
manual says that array_reduce is iterative, so this should be pretty speedy).
----
Manual Page -- http://www.php.net/manual/en/function.implode.php
Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+35214
Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+35214&report=yes
Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+35214&report=yes