Access row and column of an array

Asked

Viewed 584 times

0

I’m a beginner in php. My code reads a csv file and stores it in an array. The problem is that I can’t access the columns. I’m using php 5.3.3. Does anyone know how to pick up the row and column?

That and my function:

    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 way out:

    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
)
  • You want to access the rows and columns yourself or want to get the values?

1 answer

0


In php it is very easy to create and manipulate arrays. But here’s the thing:

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 row of the ordinal array has another associative array within.

Here:

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

To find the information within 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 this 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.

  • but as I do to take for example the first column, element 3?

  • Thanks, it worked out!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.