问题
I have a multidimensional array $BlockData[]
which has 13 dimensions in it and 'n' number of array elements. I need to implode this array back to a single long string where the elements are separated by "\n"
line feeds and the dimensions are separated by "\t"
tabs.
I've tried using the array_map()
function with no success and need help accomplishing this. Please help!
回答1:
Here's an option that I suggested yesterday in chat:
$callback = function($value) {
return implode("\t", $value);
};
echo implode("\n", array_map($callback, $BlockData));
Or, if you're using PHP < 5.3 (5.2, 5.1, 5.0, etc)
$callback = create_function('$value', 'return implode("\t", $value);');
echo implode("\n", array_map($callback, $BlockData));
回答2:
This can be done using a recursive function
<?php
function r_implode( $pieces )
{
foreach( $pieces as $r_pieces )
{
if( is_array( $r_pieces ) )
{
$retVal[] = "\t". r_implode( $r_pieces );
}
else
{
$retVal[] = $r_pieces;
}
}
return implode("\n", $retVal );
}
$test_arr = array( 0, 1, array( 'a', 'b' ), array( array( 'x', 'y'), 'z' ) );
echo r_implode( $test_arr ) . "\n";
$test_arr = array( 0 );
echo r_implode( $test_arr ) . "\n";
?>
回答3:
$lines = array();
foreach($BlockData as $data) {
$lines[] = implode("\t", $data);
}
echo implode("\n", $lines);
I would like to give credit to @Alex for recommending this, then deleting his post. This solution worked for me.
来源:https://stackoverflow.com/questions/5259947/php-implode-multidimensional-array-to-tab-dilimited-lines