1

I am currently trying to use PHP to get some information from a csv file. I am using the following code and getting the following output;

function readCSV($csvFile){
    $file_handle = fopen($csvFile, 'r');
    while (!feof($file_handle) ) {
        $line_of_text[] = fgetcsv($file_handle, 1024);
    }
    fclose($file_handle);
    return $line_of_text;
}

$csvFile = '500.csv';
$csv = readCSV($csvFile);
$keys = $csv[0];
$step = $csv[1];
foreach ($step as $k=>$v)
{
    $a = array("$keys[$k]");
    $b = array("$v");
    $c = array_combine($a, $b);
    echo '<pre>';
    print_r($c);
    echo '</pre>';
}

and I get the output in individual arrays like;

Array
(
    [first_name] => bob
)
Array
(
    [last_name] => smith
)
Array
(
    [company_name] => bobs logs
)

and I want the output to be in one single array, displayed like;

Array
(
    [first_name] => bob
    [last_name] => smith
    [company_name] => bobs logs
)

If anyone could point out where I am going wrong it would be appriciated!

1
  • Since you have 3 arrays, you could just do repl.it/Cg3C $a + $b + $c Commented Jul 27, 2016 at 14:09

3 Answers 3

3

array_combine function

Returns the combined array, FALSE if the number of elements for each array isn't equal.

Your code creates a new array on each loop iteration.
To get a single array change your loop code as shown below:

...
$c = [];
foreach ($step as $k => $v)
{
    $c[$keys[$k]] = $v;    
}
echo '<pre>';
print_r($c);
echo '</pre>';
Sign up to request clarification or add additional context in comments.

Comments

2

Change:

$a = array("$keys[$k]");
$b = array("$v");
$c = array_combine($a, $b);

To:

$c[$keys[$k]] = $v;

And do this after the loop:

echo '<pre>';
print_r($c);
echo '</pre>';

Comments

1
<?php
function readCSV($csvFile)
{
    $file_handle = fopen($csvFile, 'r');
    while (!feof($file_handle)) {
        $line_of_text[] = fgetcsv($file_handle, 1024);
    }
    fclose($file_handle);
    return $line_of_text;
}

$csvFile = '500.csv';
$csv     = readCSV($csvFile);
$keys    = $csv[0];
$step    = $csv[1];
$output = array();
foreach ($step as $k => $v) {
    $a = array("$keys[$k]");
    $b = array("$v");
    $c = array_combine($a, $b);
    $output = array_merge($output, $c);
}
echo '<pre>';
print_r($output);
echo '</pre>';

what changes did I make? I took outside foreach those echo and print_r and added

$output = array_merge($output, $c);

Which merge every new array as a new element inside our $output array

then finally we print $output array.

This should be working as you want, anyway if you need to change something in the future you can check array_merge function here

1 Comment

You should explain your answer some more.

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.