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()?
It depends on your definition of better in this context. I think your solution is good enough. Is better:
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With