Access row and column of an array

0

I'm a beginner in php. My code le a csv file and saves it in an array. The problem is that I can not access the columns. I'm using php 5.3.3. Does anyone know how I get the line and the column?

This is my role:

    function readCsv($fileName)
 {
     if(!file_exists($fileName) || !is_readable($fileName)) return false;

 $header = null;
 $data = array();
 $lines = file($fileName);

 foreach($lines as $line) {
     $values = str_getcsv($line, ',', '\');
     if(!$header) $header = $values;
     else $data[] = array_combine($header, $values);
 }

 return $data;

}

And this is my exit:

    Array
(
    [Section #] => 
    [Q #] => 1
    [Q Type] => MAT
    [Q Title] => 
    [Q Text] => Please rank your 6 preferred sites for your practicum:
    [Bonus?] => 
    [Difficulty] => 
    [Answer] => Boniface (STB)
    [Answer Match] => Rank 2
    [# Responses] => 0
)
Array
(
    [Section #] => 
    [Q #] => 1
    [Q Type] => MAT
    [Q Title] => 
    [Q Text] => Please rank your 6 preferred sites for your practicum:
    [Bonus?] => 
    [Difficulty] => 
    [Answer] => Boniface (STB)
    [Answer Match] => Rank 2
    [# Responses] => 0
)
Array
(
    [Section #] => 
    [Q #] => 1
    [Q Type] => MAT
    [Q Title] => 
    [Q Text] => Please rank your 6 preferred sites for your practicum:
    [Bonus?] => 
    [Difficulty] => 
    [Answer] => Boniface (STB)
    [Answer Match] => Rank 2
    [# Responses] => 0
)
    
asked by anonymous 15.08.2018 / 06:13

1 answer

0

In php it is very easy to create and manipulate arrays. But it is as follows:

In your code you want to access a row and column of an array. For each row of the array, you are creating an array with the index being $ header and the value being $ values.

This means that each line of the ordinal array has another associative array inside.

Here:

$data[] = array_combine($header, $values);

To find the information inside this array, you need to give the index of the $ data array and it will return another array.

For example:

print_r($data[0]) will return more or less:

Array
(
    [Section #] => 
    [Q #] => 1
    [Q Type] => MAT
    [Q Title] => 
    [Q Text] => Please rank your 6 preferred sites for your practicum:
    [Bonus?] => 
    [Difficulty] => 
    [Answer] => Boniface (STB)
    [Answer Match] => Rank 2
    [# Responses] => 0
)

Then you access inside that array the information you want. For example:

for($i=0;$i<count($data);$i++){
  $info = $data[$i];

  // agora vamos acessar a Q Text ou qualquer outra coisa

  echo $info["Q Text"] . "<br>";
  echo $info["Answer"];
}

You can also read about arrays in php.net.

    
15.08.2018 / 14:02