PHP explode and assign it to a multi-dimensional array

rakibtg picture rakibtg · Jan 30, 2014 · Viewed 12.3k times · Source

i want to explode a string two time and make a multi-dimensional array.

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

so a print_r($data); will output:

Array
(
    [0] => i love funny movies 
    [1] =>  i love stackoverflow com 
    [2] =>  i like rock song
)

now if i do like this:

$line_data = explode(" ", $data); // explode $data variable by spaces.

a print_r($line_data); will give me this:

Array
(
    [0] => i
    [1] => love
    [2] => funny
    [3] => movies
    [4] => 
    [5] => i
    [6] => love
    [7] => stackoverflow
    [8] => dot
    [9] => com
    [10] => 
    [11] => i
    [12] => like
    [13] => rock
    [14] => song
)

but what i want to achive will look like this:

Array
(
    [0][0] => i
    [0][1] => love
    [0][2] => funny
    [0][3] => movies
    [0][4] => 
    [1][5] => i
    [1][6] => love
    [1][7] => stackoverflow
    [1][8] => dot
    [1][9] => com
    [1][10] => 
    [2][11] => i
    [2][12] => like
    [2][13] => rock
    [2][14] => song
)

here, the first index should represent the line number and second index will represent the word number.
How to explode the string to have such array?

Answer

voodoo417 picture voodoo417 · Jan 30, 2014

Do it:

$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>';

OUTPUT (what you need):

Array
(
  [0] => Array
    (
        [0] => i
        [1] => love
        [2] => funny
        [3] => movies
        [4] =>  
    )

[1] => Array
    (
        [5] => i
        [6] => love
        [7] => stackoverflow
        [8] => dot
        [9] => com
        [10] =>  
    )

[2] => Array
    (
        [11] => i
        [12] => like
        [13] => rock
        [14] => song
    )

)