简体   繁体   English

删除多维数组中的键

[英]Remove key in multidimensional array

I want to delete key [Price] but the function which I use for deletion doesn't work for this case 我想删除键[价格],但我用于删除的功能在这种情况下不起作用

I have: 我有:

Array(
       [Values] => 1
       [Product] => Array( 
                           [Details] => Array( 
                                              [ID] => 1
                                              [Price] => Array(
                                                              )
                                             )
                         )
    )

My goal is: 我的目标是:

Array(
       [Values] => 1
       [Product] => Array( 
                           [Details] => Array( 
                                              [ID] => 1
                                             )
                         )
    )

I use this for removal: 我用它来去除:

function remove_key($array, $key)
        {
            foreach($array as $k => $v) {

                if(is_array($v)) {
                    $array[$k] = remove_key($v, $key);
                } elseif($k == $key) {
                    unset($array[$k]);
                }
            }
            return $array;
        }

$array = remove_key($array,'Price');

What is wrong here? 怎么了

<?php
$array = Array(
    'Values' => 1,
 'Product' => Array(
    'Details' => Array(
        'id' => 1,
        'Price' => Array(
)
      )
   )
);



unset($array['Product']['Details']['Price']);
echo "<pre>";
print_r($array);
echo "</pre>";

And the output is : 输出为:

Array
(
    [Values] => 1
    [Product] => Array
        (
            [Details] => Array
                (
                    [id] => 1
                )

        )

)

so if you want to fix your function you must add another condition into first if as so && $k != $key because you are not getting into elseif and unset is not called 因此,如果要修复函数,则必须先添加另一个条件( if这样的话&& $k != $key因为您没有进入elseif并且未调用unset

  function remove_key($array, $key)
        {
            foreach($array as $k => $v) {
                if(is_array($v) && $k != $key) {
                    $array[$k] = remove_key($v, $key);
                } elseif($k == $key) {
                    unset($array[$k]);
                }
            }
            return $array;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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