Joe Remsen
Joe Remsen

Reputation: 13

Convert text with two delimiters into an array of indexed arrays

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];

Upvotes: 0

Views: 82

Answers (3)

SirPilan
SirPilan

Reputation: 4857

You can use str_getcsv aswell after exploding your data by #.

array_map will replace every element by the return value of the given function str_getcsv.

$alldata = 'audi,bmw,mercedes#volvo,fiat,seat#A,B,C';

$data = array_map('str_getcsv', explode('#', $alldata));

Working example.

Upvotes: 0

simon.ro
simon.ro

Reputation: 3312

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

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 79014

It is much easier. Just explode, loop and explode creating a new array of rows with an array of columns:

$tablerow = explode("#", $alldata);

foreach($tablerow as $row) {
    $result[] = explode(',', $row);
}

Upvotes: 0

Related Questions