Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Arrays - read from CSV file, make first column key, second column value

Tags:

arrays

php

I have a CSV file as follows:

first-key,first-value
second-key,second-value
third-key,third-value
fourth-key,fourth-value

I am reading these in to an array using:

$tmp_array = array_map('str_getcsv', file('./values.csv'));

However, this results in this array:

Array
(
    [0] => Array
        (
            [0] => first-key
            [1] => first-value
        )

    [1] => Array
        (
            [0] => second-key
            [1] => second-value
        )

    [2] => Array
        (
            [0] => third-key
            [1] => third-value
        )

    [3] => Array
        (
            [0] => fourth-key
            [1] => fourth-value
        )

)

What I would like is this array:

Array
(
    [first-key] => first-value
    [second-key] => second-value
    [third-key] => third-value
    [fourth-key] => fourth-value
)

One way I can achieve this is by doing this:

$tmp_array = array_map('str_getcsv', file('./values.csv'));
$array = [];
foreach ($tmp_array as $row) {
    $array[$row[0]] = $row[1];
}

Is there a better way of doing this? Perhaps using array_map()?

like image 282
Scott Deagan Avatar asked Mar 19 '26 00:03

Scott Deagan


1 Answers

It depends on your definition of better in this context. I think your solution is good enough. Is better:

  • not using foreach?
  • less lines?
  • less variables?
  • using more standard library functions?

I want to post 2 propositions:

// 1
$tmp = array_map('str_getcsv', file('data.csv'));
$data = array_combine(array_column($tmp, 0), array_column($tmp, 1));

var_dump($data);

// 2
$data = [];
array_walk(
  $tmp,
  function($e) use (&$data) {$data[$e[0]] = $e[1];}
);

var_dump($data);

Output:

array(4) {
  ["first-key"]=>
  string(11) "first-value"
  ["second-key"]=>
  string(12) "second-value"
  ["third-key"]=>
  string(11) "third-value"
  ["fourth-key"]=>
  string(12) "fourth-value"
}
array(4) {
  ["first-key"]=>
  string(11) "first-value"
  ["second-key"]=>
  string(12) "second-value"
  ["third-key"]=>
  string(11) "third-value"
  ["fourth-key"]=>
  string(12) "fourth-value"
}
like image 146
blahy Avatar answered Mar 21 '26 13:03

blahy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!