Read CSV and save to variable array

Asked

Viewed 9,998 times

3

I have a code where I read the EXCEL file. CSV and display the data on the screen, but I need to save these values in an array.

My code:

<?php
$file = fopen(numeros.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE)
{
  //$line is an array of the csv elements
  print_r($line);
}
fclose($file);
?>

$arrayItem= array('8532300022', '8501022934', '8501022969', '8501022926', '8501022985'); 

It would have to look something like:

$arrayItem= array('$line');

Valew

  • 1

    Good afternoon, seeing the questions you asked, I think the problem is that you are not understanding well how the PHP language works and it seems to me that you are wanting to apply some "your head" logics that do not make much sense, I say this because the author of the answer here show you how you use php and you want it in a way that I don’t know in any language I’ve programmed. I hope you don’t take this as a constructive criticism for your learning.

1 answer

4


Try this:

$meuArray = Array();
$file = fopen('numeros.csv', 'r');
while (($line = fgetcsv($file)) !== false)
{
  $meuArray[] = $line;
}
fclose($file);
print_r($meuArray);

And to use the values of $meuArrray, just use a for or a foreach or simply set an index in the variable:

for($i = 0; $i < count($meuArray); $i++){
echo $meuArray[$i];
}

or

foreach($meuArray as $linha => $valor){
echo 'linha '.$linha.' = '.$valor;
}

  • It worked, but I would like to do something in this format, ( $arrayItem = array($meuArray); )

  • Do not understand, try to explain a little more. The way I suggested, you are already saving an answer per line.

  • The result appears like this: ( [108] => Array ( [0] => 8501060631 ) ) How do I just take the value of the array, ne case is the number 8501060631

  • What is $arrayItem? Try to add at least a piece of your csv and show how Voce wants to separate the data.

  • I am using this code http://answall.com/questions/96197/erro-webservice/96227?noredirect=1#comment196548_96227

  • You want to save a new Array in $arrayItem only with the values of $meuArray? It doesn’t make any sense. Just use the $meuArray within a repeat loop. I will edit the code.

  • I can ask just one more question ?

  • @Developer I edited the code, now does what you suggested.

  • I’ll explain better what I need

  • 1

    @Developer You have completely changed the context of the question and this is not recommended as the answers are meaningless. Return the question as it was, mark as solved and create another with the new doubt

Show 6 more comments

Browser other questions tagged

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