3

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!

sadmicrowave
  • 39,964
  • 34
  • 108
  • 180
  • Based upon the [example in chat](http://chat.stackoverflow.com/transcript/message/442408#442408), this is not a 13 dimension array, it is a 2 dimension array with 9 elements inside of it. – ircmaxell Mar 10 '11 at 14:15
  • possible duplicate of [PHP: Implode data from a multi-dimensional array](http://stackoverflow.com/questions/16710800/php-implode-data-from-a-multi-dimensional-array) –  Nov 23 '13 at 05:27

3 Answers3

5

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";
?>
Jon Skarpeteig
  • 4,118
  • 7
  • 34
  • 53
2

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));
ircmaxell
  • 163,128
  • 34
  • 264
  • 314
0
 $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.

sadmicrowave
  • 39,964
  • 34
  • 108
  • 180