boctulus
boctulus

Reputation: 395

Access php array index issue

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 ?

Upvotes: 0

Views: 62

Answers (2)

boctulus
boctulus

Reputation: 395

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!

Upvotes: 0

Vinie
Vinie

Reputation: 2993

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++;
 }

Upvotes: 1

Related Questions