Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php implode multidimensional array to tab dilimited lines

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!

like image 501
sadmicrowave Avatar asked Apr 20 '26 10:04

sadmicrowave


2 Answers

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";
?>
like image 129
Jon Skarpeteig Avatar answered Apr 23 '26 01:04

Jon Skarpeteig


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));
like image 45
ircmaxell Avatar answered Apr 23 '26 01:04

ircmaxell