Search code examples
phparraysmultidimensional-arrayexplode

Explode and assign it to a multi-dimensional array


I found this code in another post which I found quite helpful but for me it's only half the equation. In line with the following code, I need to take the string from a database, explode it into the 2d array, edit values in the array and implode it back ready for storage in the same format. So specifically backwards in the same order as the existing script.

The code from the other post >>

$data = "i love funny movies \n i love stackoverflow dot com \n i like rock song";
$data = explode(" \n ", $data);

$out = array();
$step = 0;
$last = count($data);
$last--;

foreach($data as $key=>$item){

   foreach(explode(' ',$item) as $value){
    $out[$key][$step++] = $value;
   }

   if ($key!=$last){
    $out[$key][$step++] = ' '; // not inserting last "space"
   }

}

print '<pre>';
print_r($out);
print '</pre>';

Solution

  • The quoted code inserts separate array elements which just have a space as value. One can wonder what benefit those bring.

    Here are two functions you could use:

    function explode2D($row_delim, $col_delim, $str) {
        return array_map(function ($line) use ($col_delim) {
            return explode($col_delim, $line);
        }, explode($row_delim, $str));
    }
    
    function implode2D($row_delim, $col_delim, $arr) {
        return implode($row_delim, 
            array_map(function ($row) use ($col_delim) {
                return implode($col_delim, $row);
            }, $arr));
    }
    

    They are each other's opposite, and work much like the standard explode and implode functions, except that you need to specify two delimiters: one to delimit the rows, and another for the columns.

    Here is how you would use it:

    $data = "i love funny movies \n i love stackoverflow dot com \n i like rock song";
    
    $arr = explode2D(" \n ", " ", $data);
    
    // manipulate data
    // ...
    $arr[0][2] = "scary";
    $arr[2][2] = "balad";
    
    // convert back
    
    $str = implode2D(" \n ", " ", $arr);
    

    See it run on repl.it.