phparraysmultidimensional-arraysplitexplode

Convert text with two delimiters into a 2d array


I have a file called data.txt with the following inside: (three groups containing each three cars)

"audi,bmw,mercedes#volvo,fiat,seat#peugeot,..." 

and so on, you get the idea.

Splitting the "groups" by the # with the php explode() works perfectly fine. However, when I'm trying to split the groups by the komma, it does not work the way I want it to:

For "$tablerow[0][1];" I just get the letter "u"(second letter) instead of "bmw" (second word as intended).

Where is my mistake (Code below)?

The $index_number just counts the number of those groups.

$datafile = fopen("data.txt","r"); <br>
$alldata = fread($datafile,filesize("data.txt")); <br>
$tablerow = explode("#",$alldata); <br>

for ($arrayposition = 0; $arrayposition <= $index_number; ++$arrayposition) { <br>
for ($tablerowindex = 0; $tablerowindex <= 3; ++$tablerowindex) { <br>
$tablecolumn = explode(",",$tablerow[$tablerowindex]); <br>
} <br>
} <br>
echo $tablerow[0][1];

Solution

  • After $tablerow = explode("#",$alldata); $tablerow is an array of comma-separated cars. e.g. $tablerow[0] == 'audi,bmw,mercedes'.

    Later you loop over that array and split every element. But you don't touch the $tablerow anymore. $tablerow stays what it is. So $tablerow[0][1] references the second character of the first element, which is "u"

    What you probably need is something like

    $alldata='audi,bmw,mercedes#volvo,fiat,seat#peugeot';
    $table = [];
    foreach (explode("#", $alldata) as $carGroup) {
        $table[] = explode(",", $carGroup);
    }
    
    // $table[0][0] => audi
    // $table[0][1] => bmw