Reputation: 8602
I am uploading a CSV file/report with 10 columns but at the end of the CSV file there are a few lines that just give details about the report like
Generated By: XXX
Company Name
Report Run @ 2019-03-14
When I load the array, the keys are just numeric (from 0-9) but I wanted to make it be an associative array based on the column headers. Unfortunately this will not work for the last few lines since the array dimensions are different (1 vs 10)
Here is my code:
$csv = array_map('str_getcsv', file($_FILES['file']['tmp_name']));
array_walk($csv, function(&$a) use ($csv) {
if(count($csv[0]) != count($a)) {
$a = null; // Remove the array
} else {
$a = array_combine($csv[0], $a);
}
});
array_shift($csv); # remove column header
When I do $a = null;
it sort of 'deletes it' by replacing it with NULL
. When I iterate through the arrays I do if(is_null($row)) continue;
to ignore the NULL
element. Is there a way to actually delete the array?
Upvotes: 0
Views: 87
Reputation: 41810
I think it's more straightforward without array_walk
. array_walk
is just going to apply the function to every member of the array. Setting it to null doesn't mean it's gone, it just has a null value as you've seen. If you really want it gone, you need to unset it. Just refer to $csv
by key and unset the ones you don't want.
$keys = array_shift($csv);
$expected_count = count($keys);
foreach ($csv as $index => $values) {
if (count($values) == $expected_count) {
$csv[$index] = array_combine($keys, $values);
} else {
unset($csv[$index]);
}
}
Upvotes: 2
Reputation: 808
Array_filter($csv); afterwards will remove all null/false/0 from your array.
So it may be smarter to write a custom function to remove null only.
Upvotes: 0