0

I have an array generated from some code:

if (($handle = fopen('/var/tmp/file.tsv', 'r')) !== FALSE) {
    $nn = 0;
    while (($data = fgetcsv($handle, 1000, '/t')) !== FALSE) {
        $targetData = array();                 
        foreach($targetColumns as $column)      
        $targetData[] = $data[$column]; 
        $csvarray[$nn] = $targetData;
        $nn++;
    }
    fclose($handle);
}

This gives me this output:

Array
(
  [0] => Array
    (
        [0] => "92834029"
    )
  [1] => Array
    (
        [0] => "32926154"
    )
  [2] => Array
    (
        [0] => "84892302"
    )
  [3] => Array
    (
        [0] => "10499507"
    )
)

How do I do away with the multidimension arrays and instead make it one clean simple parent array?

Array
(
  [0] => 92834029
  [1] => 32926154
  [2] => 84892302
  [3] => 10499507
)
user1899415
  • 3,015
  • 7
  • 22
  • 31
  • Do you mean you want to [flatten the array](http://stackoverflow.com/questions/1319903/how-to-flatten-a-multidimensional-array/1320156)? – Dan Nov 07 '13 at 19:55
  • 1
    change this: $targetData[] = $data[$column]; $csvarray[$nn] = $targetData; to this: $csvarray[$nn] = $data[$column]; – busypeoples Nov 07 '13 at 19:55
  • @busypeoples's fix worked! thanks really appreciate it. – user1899415 Nov 07 '13 at 20:09

2 Answers2

4

In your case changing it to the following will work:

if (($handle = fopen('/var/tmp/file.tsv', 'r')) !== FALSE) {        
    while (($data = fgetcsv($handle, 1000, '/t')) !== FALSE) {              
        foreach($targetColumns as $column) {          
            $csvarray[] = $data[$column];
        }
    }
    fclose($handle);
}

Took the liberty of removing unnecessary stuff too.

Allain Lalonde
  • 91,574
  • 70
  • 187
  • 238
2

Try to do it that way:

if (($handle = fopen('/var/tmp/file.tsv', 'r')) !== FALSE) {
  $nn = 0;
  while (($data = fgetcsv($handle, 1000, '/t')) !== FALSE) {
    foreach($targetColumns as $column)      
    $targetData = $data[$column]; 
    $csvarray[$nn] = $targetData;
    $nn++;
  }
  fclose($handle);
}

The $targetData is always kind of 'nulled' by the = array() anyway. Or assign it directly with $csvarray[$nn] = $data[$column];.

Andreas
  • 2,694
  • 2
  • 21
  • 33