0

After use fgetcsv() function I get an array, then I use a foreach() and I get a "simple" associative array like:

Array  
(  
  [ix,radical,variant,simplified,pinyin,english,strokes] => 1,一,,,yi1,one,1  
)  

Then I try to access any element and I fail:

 echo $record['ix'];

Notice: Undefined index: ix

echo next($record);  // return nothing!

Maybe is offtopic (not centred in php language) but I'm using some lib (not necessary of course from PHP commenter in http://php.net/manual/es/function.fgetcsv.php)

<?php

require "..\CsvImporter.lib.php";

$importer = new CsvImporter('my_route\\my.csv',true); 
while($records = $importer->get()) 
{   
    // debug
    print_r($records[0]);
    exit; 

    foreach ($records as $record)   
    {
      \\ ..
    }
}

And my screen output is

Array ( [ix,radical,variant,simplified,pinyin,english,strokes] => 1,一,,,yi1,one,1 )

My data:

ix,radical,variant,simplified,pinyin,english,strokes
1,一,,,yi1,one,1
2,丨,,,gun3,line,1
3,丶,,,zhu3,dot,1

So how is possible I'm unable to access any key ?

12
  • Please properly print your array with key and value. Commented Mar 11, 2016 at 12:58
  • Milap, that was my array! Commented Mar 11, 2016 at 12:58
  • @Boctulus I think you probably want to show us your code how you tried to construct your array, because your key is not ix but ix,radical,variant,simplified,pinyin,english,strokes. Show: your current code to build this array and what you expect to get Commented Mar 11, 2016 at 12:59
  • Your array is not correct. Kindly review it again. That's a wrong format of array. Php dosent makes syntax error. Commented Mar 11, 2016 at 13:06
  • Try print_r($record); exit; and see what it prints out. Commented Mar 11, 2016 at 13:07

2 Answers 2

1

As you posted your data above. Your csv importer giving you each row with comma. So you need to explode it then use however you want to use

Example code \

 $i=0;
 while($records = $importer->get()) 
 {   
      if($i>0) //skip first row it is heading
      {
           $data = explode(',',$records);
           print_r($data);
          // now `$data[0]` contains `ix` value for your first csv row and so on
      }
      $i++;
 }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I know how to do it in a lot of ways, but I was wondering why couldn't access that array in particular. Good answer anyway
0

I used some lib and the default delimiter was "\t" so something like 'ix,radical,variant,simplified,pinyin,english,strokes' was THE key and '一,,,yi1,one,1' the only value

Now, I see the problem I can do it easy:

$f = 'file.csv';
$separator = ',';

$file = file_get_contents($f);     

// bi-dimensional array
$regs = array_map(function($reg){return (explode($separator,$reg));},explode("\n",$file));

Thanks all!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.