PHP: Delete Array from 2D-Array

11
March 15, 2019, at 10:20 PM

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?

Answer 1

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]);
    }
}
Answer 2

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.

READ ALSO
Remove id from url in htaccess

Remove id from url in htaccess

How do I remove the id from the url and pass it with GET?

48
I'm trying to creat and store a file locally in my pc using any web programing language

I'm trying to creat and store a file locally in my pc using any web programing language

I'm trying to save a txt file in my pc locally with php, but not in the download folderI need to add in different folder

26
Grabbing userID and field upon user creation

Grabbing userID and field upon user creation

I currently have a function that simply creates a user record in the database

13
Submitting 2 Forms with 1 Button or 1 Input

Submitting 2 Forms with 1 Button or 1 Input

currently i have 2 Buttons (well 1 Button and 1 Input with a Bootstrap button class) I use to upload a picture, and add a text to that picutre

10