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] => 
        )

)
compcobalt
  • 1,322
  • 7
  • 31
  • 61

4 Answers4

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
?>
Manav
  • 1,357
  • 10
  • 17
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));
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
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);
LostCause
  • 151
  • 1
  • 11
-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

Sebastian Sulinski
  • 5,815
  • 7
  • 39
  • 61