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
)
3
  • Do you mean you want to flatten the array? Commented Nov 7, 2013 at 19:55
  • 1
    change this: $targetData[] = $data[$column]; $csvarray[$nn] = $targetData; to this: $csvarray[$nn] = $data[$column]; Commented Nov 7, 2013 at 19:55
  • @busypeoples's fix worked! thanks really appreciate it. Commented Nov 7, 2013 at 20:09

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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];.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.