PHP: remove element from multidimensional array (by key) using foreach

前端 未结 4 1781
执念已碎
执念已碎 2020-12-03 18:34

I got multidimensional array. From each subarray, I would like to remove / unset values with index 1. My array $data.

Array
(
    [3463] => Array
                 


        
相关标签:
4条回答
  • 2020-12-03 19:00

    try this:

    <?php 
        $data = Array
        (
            '3463' => Array
                (
                    '0' => 1,
                    '1' => 2014,
                    'context' => 'aaa'
                ),
    
            '3563' => Array
                (
                    '0' => 12,
                    '1' => 2014,
                    'context' => 'aaa'
                ),       
    
            '2421' => Array
                (
                    '0' => 5,
                    '1' => 2014,
                    'context' => 'zzz'
                )               
        );
    
        foreach ($data as $k=>$subArr) {
            foreach ($subArr as $key => $value) {
    
                if ($key == '1') {
                    unset($data[$k][$key]);
                }
    
            }
        }
    print_r($data);// display the output
    
    0 讨论(0)
  • 2020-12-03 19:01

    It does not work because $subArr from the outer foreach contains copies of the values of $data and the inner foreach modifies these copies, leaving $data not touched.

    You can fix that by telling PHP to make $subArr references to the original values stored in $data:

    foreach ($data as &$subArr) {
       foreach ($subArr as $key => $value) {
           if ($key == '1') {
            unset($subArr[$key]);
           }
       }
    }
    

    Another option is to use function array_map(). It uses a callback function that can inspect (and modify) each value of $data and it returns a new array.

    $clean = array_map(
        function (array $elem) {
            unset($elem['1']);        // modify $elem
            return $elem;             // and return it to be put into the result
        },
        $data
    );
    
    print_r($clean);
    
    0 讨论(0)
  • 2020-12-03 19:19

    you are making changes in subarray instead of main one try this may help

    foreach ($data as $key => $subArr) { 
        unset($data[$key][1]);      
    }
    
    0 讨论(0)
  • 2020-12-03 19:21

    easy way!? you can do this just with one foreach!

    foreach ($data as $key => $subArr) {
        unset($subArr['1']);
        $data[$key] = $subArr;  
    }
    
    0 讨论(0)
提交回复
热议问题