Try this:

function delete_row(&$array, $offset) {
    return array_splice($array, $offset, 1);
}

function delete_col(&$array, $offset) {
    return array_walk($array, function (&offset) {
        array_splice(offset, 1);
    });
}

Tested on Ideone: http://ideone.com/G5zRi0

Edit (Amade):

delete_col function can also be slightly modified to work with arrays with missing columns:

function delete_col(&$array, $key) {
    return array_walk($array, function (&key) {
        unset(key]);
    });
}

This can be used e.g. when you need to iterate over an array and remove some columns in each step. A function using array_splice instead of unset would not be appropriate in such scenarios (it's offset-based and not key-based).

Answer from mpyw on Stack Overflow
🌐
Reddit
reddit.com › r/phphelp › how to remove columns from an associative array?
r/PHPhelp on Reddit: How to remove columns from an associative array?
December 13, 2022 -

I have this array which is used to generate an excel file using PhpSpreadsheet. This is the array

$data =
    array(
        1 =>
        array(
            'A' => 'Project',
            'B' => 'Execution.Key',
            'C' => 'Execution.Assigned To',
            'D' => 'Execution.Type',
            'E' => 'Execution.Execution Date',
            'F' => 'Execution.Actual',
            'G' => 'Execution.Estimated',
            'H' => 'Execution.Result',
            'I' => 'Execution.Environment',
        ),
        2 =>
        array(
            'A' => 'FOO',
            'B' => 'FOO-KEY',
            'C' => '',
            'D' => 'MANUAL',
            'E' => '2022-12-09',
            'F' => NULL,
            'G' => NULL,
            'H' => 'Not Executed',
            'I' => NULL,
        )
    );

I want to remove these columns from that array

$unwanted_cols = [
    "Execution.Assigned To",
    "Execution.Execution Date",
    "Execution.Actual",
    "Execution.Estimated",
    "Execution.Result",
    "Execution.Environment",
];

So in this example, we should only have these columns

$result = [
 'A' => 'Project',
 'D' => 'Execution.Type'
]

So we remove the item using the key

  function delete_cols($data, $unwanted_cols)
    {
        $cols_to_delete = [];
        if (isset($data[1])) {
            $headers = $data[1];

            foreach ($headers as $key => $value) {
                if (in_array($value, $unwanted_cols)) {
                    array_push($cols_to_delete, $key);
                }
            }
            foreach ($data as $key => $value) {
                if (!in_array($key, $cols_to_delete)) {
                    unset($data[$key]);
                }
            }
        }
        return $data;
    }
}

 

it's not working though, why?

I don't want to remove by value, I want to remove by key, meaning if

'C' => 'Execution.Assigned To'

is in the $cols_to_delete array, then I want to loop the entire array and remove all values having the key 'C', which means I want to remove column C from the spreadsheet

Discussions

How to delete a column of a multidimensional array in php? - Stack Overflow
I am trying to remove the second element from every row of multidimensional array. I have only found solutions to remove the last array or to remove the last column. Here's my latest trying, but doesn't work now... Can you help me? "1", "item_name" => "a"], ["item_id" ... More on stackoverflow.com
🌐 stackoverflow.com
php - How to remove multiple columns from the multi dimensional array? - Stack Overflow
I have a multi dimensional array like below. array:1 [ 0 => array:3 [ "picture_id" => "0" "car_name" => "CA" "from" => "2020" "to" => "2020" ] ] I need to remove... More on stackoverflow.com
🌐 stackoverflow.com
April 23, 2020
php - Remove "columns" from the subarrays of a two dimensional array - Stack Overflow
I'm trying to write an efficient function which will return an array with only the first 'n' columns of each subarray. More on stackoverflow.com
🌐 stackoverflow.com
September 13, 2010
php - removing array from multidimensional array - Stack Overflow
As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value. More on stackoverflow.com
🌐 stackoverflow.com
November 13, 2011
🌐
Prodevsblog
prodevsblog.com › questions › 173990 › best-way-to-delete-column-from-multidimensional-array
Q&A ProDevsBlog | Best way to delete “column” from multidimensional array
July 27, 2020 - The other question is how to return x columns. These are different questions. ... The first comment on the accepted answer to the question your posted says it all really. ... That answer is 4 lines, can't get much simpler than that. It only uses the function you yourself provided combined with a foreach loop... ... function delete_row(&$array, $offset) { return array_splice($array, $offset, 1); } function delete_col(&$array, $offset) { return array_walk($array, function (&$v) use ($offset) { array_splice($v, $offset, 1); }); }
Find elsewhere
🌐
PHP Freaks
forums.phpfreaks.com › php coding › php coding help
Remove related element from multidimensional array - PHP Coding Help - PHP Freaks
May 23, 2018 - array · By thara May 22, 2018 in PHP Coding Help · Share · https://forums.phpfreaks.com/topic/307295-remove-related-element-from-multidimensional-array/ More sharing options... Followers 1 · Go to solution Solved by Barand, May 22, 2018 · Reply to this topic ·
🌐
GitHub
gist.github.com › wisbey › 3826550
PHP: removing row from a multidimensional array if empty · GitHub
PHP: removing row from a multidimensional array if empty - PHP remove empty row from array
🌐
PHP
php.net › manual › en › function.array-column.php
PHP: array_column - Manual
array is treated as a list of rows, each of which is itself an array or an object; a column is the entry or property that column_key names in every row. Rows that are neither an array nor an object, and rows in which that entry or property is absent, are skipped without a diagnostic. The keys of array are never preserved. ... A list whose rows are arrays or objects, from which a column of values is pulled.
🌐
PHP Freaks
forums.phpfreaks.com › php coding › php coding help
Remove a row from a Multidimensional Array - PHP Coding Help - PHP Freaks
December 22, 2010 - I am trying to write a dirty script that removes duplicate rows from a multidimensional array. I want to be able to edit the function and spit the duplicates out to a CSV file. Here is my test file: $fullArray = array(array('Jim', 'Jones'), array('Pete', 'Pumpkin'), array('Barak', 'Obama'), array...
Top answer
1 of 2
750
Answer · Solution: · First when you dounset ($row[count($row)-2]); you are are just unsetting an index of the$row variable which is just a copy of the value from your array. So you are not deleting the value in the array. Secondly, when you do$row[count($row)-2] you are assuming your $row has numerical indexes, which is not the case here. You want to delete theitem_name index so you have to do something likeunset($array[$index]['item_name']). · for(length = count($array); length; ++$i) · { · unset($array[$i]['item_name']); · } · Copy code
2 of 2
378
Answer · Solution: · An alternative to aforeach loop:array_walk() applies a user function to every item in an array: · array_walk( $arr, function(&$a){unset($a['item_name']);}); · // ^^^ Use reference here to · // work on the original array · Copy code · For example: · $arr = [ · ["item_id" => "1", "item_name" => "a"], · ["item_id" => "2", "item_name" => "b"], · ["item_id" => "3", "item_name" => "c"], · ["item_id" => "4", "item_name" => "d", "value" => "10"], · ["item_id" => "5", "item_name" => "e", "value" => "11"], · ["item_id" => "6", "item_name" => "f", "value" => "12"] · ]; · array_walk( $arr, function(&$a){unset($a['item_name']);}); · print_r($arr); · /* Output · Array · ( · [0] => Array · ( [item_id] => 1 · ) · [1] => Array · ( [item_id] => 2 · ) · [2] => Array · ( · [item_id] => 3 · ) · [3] => Array · ( [item_id] => 4 · [value] => 10 · ) · [4] => Array · ( [item_id] => 5 · [value] => 11 · ) · [5] => Array · ( [item_id] => 6 · [value] => 12 · ) · ) · */
Top answer
1 of 2
2

We can make this more simpler. Just get all column values using array_column. Use array_filter with a custom callback to remove all empty string values. If after filtering, size of array is 0, then that key needs to be unset from all subarrays.

Note: The arrow syntax in the callback is introduced since PHP 7.4.

Snippet:

<?php


$data = array (
    'HeaderRow' => Array (
        '0' => 'Employee','1' => 'LaborHours', '2' => 0.1, '3' => 0.25, '4' => 0.5, '5' => 0.8
    ),
    'r0' => Array (
        '0' => 'Joe', '1' => 5, '2' => '','3' => '', '4' => 50, '5' => ''
    ),
    'r1' => Array (
        '0' => 'Fred', '1' => 5,'2' => 10, '3' => '', '4' => '', '5' => ''
    )
);


$cleanup_keys = [];
foreach(array_keys($data['HeaderRow']) as $column_key){
    $column_values = array_column($data, $column_key);
    array_shift($column_values); // removing header row value
    $column_values = array_filter($column_values,fn($val) => strlen($val) != 0);
    if(count($column_values) == 0) $cleanup_keys[] = $column_key;
}

foreach($data as &$row){
    foreach($cleanup_keys as $ck){
        unset($row[ $ck ]);
    }
}
print_r($data);
2 of 2
0

It figures, I work on this for a day and have a moment of clarity right after posting. The answer was that I wasn't leveraging the Keys.:

function array_cleanup($array)
{
    $array = transpose($array);     
    foreach ($array as $key => $value)
    {
        $empty = true;
        foreach ($value as $subkey => $subvalue)
        {               
            if ($subkey != "HeaderRow") {
                if (!empty($subvalue))
                {
                    $empty = false;
                }
            }
        }
        if ($empty) {
            unset($array[$key]);
        }
    }
    $array = transpose($array);
    return $array;
}