PHP Multidimensional array with explode() splits wrong

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];
Answer
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
Answer
Solution:
It is much easier. Justexplode
, loop andexplode
creating a new array of rows with an array of columns:
$tablerow = explode("#", $alldata);
foreach($tablerow as $row) {
$result[] = explode(',', $row);
}
Answer
Solution:
You can use aswell after exploding your data by
#
.
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.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: mysqli::real_connect(): (hy000/2002): connection refused
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.