Reputation: 1173
I have a CSV file. The first line contains header information.
Below is an excerpt of the file (comments added).
Name, City, State, Country // header line
Tom, Jackson, Mississippi, United States // line 1
Simon, Temple, Pennsylvania, United States // line 2... etc...
I'm parsing this CSV into an array using array_map:
// parse CSV file into an array
$fileArray = array_map('str_getcsv', file($file["tmp_name"]));
Which gives me the following:
array(3) {
[0] => array(4) {
[0] => string(4) "Name"
[1]=> string(4) "City"
[2]=> string(5) "State"
[3]=> string(6) "Country"
}
[1] => array(4) {
[0] => string(4) "Tom"
[1]=> string(7) "Jackson"
[2]=> string(11) "Mississippi"
[3]=> string(13) "United States"
}
[2] => array(4) {
[0] => string(5) "Simon"
[1]=> string(6) "Temple"
[2]=> string(12) "Pennsylvania"
[3]=> string(13) "United States"
}
I'm trying to remap the array to key/value pairs, so that the key will reference the appropriate header field. So for example:
array(3) {
[0] => array(4) {
['Name'] => string(4) "Name"
['City']=> string(4) "City"
['State']=> string(5) "State"
['Country']=> string(6) "Country"
}
[1] => array(4) {
['Name'] => string(4) "Tom"
['City']=> string(7) "Jackson"
['State']=> string(11) "Mississippi"
['Country']=> string(13) "United States"
}
[2] => array(4) {
['Name'] => string(5) "Simon"
['City']=> string(6) "Temple"
['State']=> string(12) "Pennsylvania"
['Country']=> string(13) "United States"
}
I'm using array_walk to alter the array with a callback function, but it appears that array_walk is having problems processing an array as the 3rd argument.
// parse CSV file into an array
$fileArray = array_map('str_getcsv', file($file["tmp_name"]));
// header line
$header = $fileArray[0]; // header[0] = "[0]=>Name, [1]=>City... etc"
/* alterArray
* Update the array to key/value
*/
function alterArray(&$item, $key, $prefix) {
$item = "${prefix}[${key}]}: ${item}";
}
// use array_walks to
array_walk($fileArray, 'alterArray', $header);
// print result
print_r($fileArray);
I'm getting this error:
Notice: Array to string conversion
Upvotes: 1
Views: 164
Reputation: 11280
Each item in alterArray
is an array, and you obviously try to cast it to string, which throws the error (just var_dump
$item
in alterArray
to see it for yourself). What you want:
function alterArray(&$item, $key, $header) {
$item = array_combine($header, $item);
}
array_walk($fileArray, 'alterArray', $header);
Upvotes: 1