简体   繁体   中英

How to delete a column of a multidimensional array in php?

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?

<?php
$array = [
    ["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"]
];

foreach($array AS $row)
{

 unset ($row[count($row)-2]);

}

print_r($array);
?>

My desired output is:

$array = [
    ["item_id" => "1"],
    ["item_id" => "2"], 
    ["item_id" => "3"], 
    ["item_id" => "4", "value" => "10"], 
    ["item_id" => "5", "value" => "11"], 
    ["item_id" => "6", "value" => "12"]
];

First when you do unset ($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 the item_name index so you have to do something like unset($array[$index]['item_name']) .

for($i = 0, $length = count($array); $i < $length; ++$i)
{
    unset($array[$i]['item_name']);
}

An alternative to a foreach 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

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
        )
)
*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM