I'm new at PHP and keep struggling to read a CSV file into a 2D-array. I use the following file 'csv/team.csv':
ID,Nickname,Shirtnumber,Position
1,Jimmy,0,RightBack
2,Mark,3,CentreBack
3,Bryan,17,LeftMidfielder
4,James,23,Striker
5,Andre,69,Goalkeeper
I would like to be able to:
- display the 'name', 'shirtnumber', 'position' etc. of individual players on a html/css-webpage.
- use the PHP-functions
prev(),current(),next()to navigate between players. - use associative keys (besides indexed keys).
My first piece of code looked like this:
$teamdata = file("csv/team.csv");
foreach ($teamdata as $playerline) {
$player = explode(",", $playerline);
list($ID,$Nickname,$Shirtnumber,$Position) = $player;
{
print_r($player); echo "<br>";
print_r(prev($player)); echo "<br>";
The result in HTML was:
Array ( [0] => 5 [1] => Andre [2] => 69 [3] => Goalkeeper )
This looks pretty cool. However,
- Why does
list()not add associative keys to the array? - Why does
prev()not work? (PHP didn't give any error-message or warning)
By introducing $myplayer, I created an array of $player.
$teamdata = file("csv/team.csv");
foreach ($teamdata as $playerline) {
$player = explode(",", $playerline);
list($ID,$Nickname,$Shirtnumber,$Position) =$player;
$myplayer[]=$player;
}
print_r($player); echo "<br>"; echo "<br>";
print_r($myplayer); echo "<br>";echo "<br>";
echo $player[1]; echo "<br>";
echo $player[3]; echo "<br>"; echo "<br>";
echo $myplayer[1][1]; echo "<br>";
echo $myplayer[2][1]; echo "<br>";
The output looked like:
Array ( [0] => 5 [1] => Andre [2] => 69 [3] => Goalkeeper )
Array ( [0] => Array ( [0] => ID [1] => Nickname [2] => Shirtnumber [3] => Position )
[1] => Array ( [0] => 1 [1] => Jimmy [2] => 0 [3] => RightBack )
[2] => Array ( [0] => 2 [1] => Mark [2] => 3 [3] => CentreBack )
[3] => Array ( [0] => 3 [1] => Bryan [2] => 17 [3] => LeftMidfielder )
[4] => Array ( [0] => 4 [1] => James [2] => 23 [3] => Striker )
[5] => Array ( [0] => 5 [1] => Andre [2] => 69 [3] => Goalkeeper ) )
Andre
Goalkeeper
Jimmy
Mark
This seems pretty much what I needed. However. I ask myself if this is the right way to do it, because:
- The function
list()can't be used - The function
prev()can't be used - Coding for selecting the correct 'player-attribute' is 'complex' and errors can easily be made
I have a background in programming COBOL (lol) and Pascal, but PHP (and Java) is totally new for me. Any advise would be welcome!
prevandnextI'm not getting it.