1

I have a csv file that looks like this:

Did,status
"123","Active"
"456","Not-Active"
"789","Active"
....and so on

I would like to be able to convert it into an array that looks like this:

$DidStatus = array("123"=>"Active", "456"=>"Not-Active", "789"=>"Active");

I tried this but it's not what I'm looking for:

$file = file_get_contents("test.csv");
$data = array_map("str_getcsv", preg_split('/\r*\n+|\r+/', $file));
print_r($data);

but the output is not the one I'm looking for:

Array
(
    [0] => Array
        (
            [0] => Did
            [1] => status
        )

    [1] => Array
        (
            [0] => 123
            [1] => Active
        )

    [2] => Array
        (
            [0] => 456
            [1] => Not-Active
        )

    [3] => Array
        (
            [0] => 789
            [1] => Active
        )

    [4] => Array
        (
            [0] => 
        )

)
7

4 Answers 4

3

Look into fgetcsv()

<?php

    $handle = fopen("test.csv", "r");
    $result = Array();
    fgetcsv($handle); //Removes the first line of headings in the csv
    while($data = fgetcsv($handle)) {
        $result[$data[0]] = $data[1];
    }
    print_r($result); //the result
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Thank you :)
3

There are other ways to do it, but given your current code, just extract an array of the 1 values and index it by the 0 values.

unset($data[0]); //If needed to remove the header row

$data = array_column($data, 1, 0);

You may consider this as an alternate for the first step (not sure if FILE_IGNORE_NEW_LINES is absolutely necessary):

$data = array_map('str_getcsv', file('test.csv', FILE_IGNORE_NEW_LINES));

Comments

0

Look into fgetcsv. That is meant to be used for something like this.

$arr = array();
$file = fopen('test.csv', 'r');
while (($result = fgetcsv($file)) !== FALSE)
{
    $arr[] = $result;
}
fclose($file);

Comments

-2

You can use this package league/csv and you can find instructions on how to use it here - one of the first examples shows how to convert csv to array

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.