【问题标题】:Class method to recursively remove keys from array从数组中递归删除键的类方法
【发布时间】:2014-03-27 12:11:01
【问题描述】:

我正在尝试编写一个简单的类来递归地从数组中删除不需要的键。没什么特别的。

<?php
class RemoveUnwantedKeysFromArrayRecursively {

    public function remove(array &$array, $keys)
    {
        $keys = (is_array($keys)) ? $keys : array($keys);

        foreach ($array as $key => &$value) {
            if(in_array($key, $keys, true)){
                unset($array[$key]);
            }

            if (is_array($value)) {
                $this->remove($value, $key);
            }
        }

        return $array;
    }
} 

但是当我对这个简单的方法进行单元测试时,我遇到了一个错误,嵌套数组始终保持不变。

class RemoveUnwantedKeysFromArrayRecursivelyTest extends \PHPUnit_Framework_TestCase {

    public function testRemove()
    {
        $remove = new RemoveUnwantedKeysFromArrayRecursively();

        $arrayTest = array('key1' => 'test', 'key2' => 'test2');
        $arrayKeys = array('key2');

        $remove->remove($arrayTest, $arrayKeys);
        $this->assertTrue(array_key_exists('key1', $arrayTest), 'test if key1 is present');
        $this->assertFalse(array_key_exists('key2', $arrayTest), 'test if key2 is present');

        $nestedArrayTest = array('key1' => 'test', 'key2' => 'test2', 'key3' => array(
        'key1' => 'nested key1', 'key2' => 'nested key2')
    );

        $remove->remove($nestedArrayTest, $arrayKeys);
        $this->assertTrue(array_key_exists('key1', $nestedArrayTest['key3']), 'test if key1 is present in the nested array');
        $this->assertFalse(array_key_exists('key2', $nestedArrayTest['key3']), 'test if key2 is present in the nested array');
    }
}

测试 key2 是否存在于嵌套数组中。断言真为假失败。

我做错了什么?我的问题类似于PHP Recursively unset array keys if match 和PHP recursive search and replace array elements,但我没有运气就读过他们的答案。

谢谢。

【问题讨论】:

    标签: php arrays class recursion phpunit


    【解决方案1】:

    在此处递归调用您的函数时,您应该传递所有 $keys 而不仅仅是一个 $key:

    $this-&gt;remove($value, $key);

    另请注意,此上下文中的 $key 来自原始数组,而不是所有要删除的键的数组。

    【讨论】:

      猜你喜欢
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 2020-06-26
      • 2019-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多