質問

I'm trying to write a simple class to remove unwanted keys from arrays recursively. Nothing special.

<?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;
    }
} 

But while I unit test this simple method, I got an error with nested arrays that remains always the same.

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');
    }
}

test if key2 is present in the nested array. Failed asserting that true is false.

What I'm doing wrong? My question is similar to PHP Recursively unset array keys if match and PHP recursive search and replace array elements but I have read their answers without luck.

Thank you.

役に立ちましたか?

解決

You shold pass all the $keys rather than just one $key when calling your function recursively here:

$this->remove($value, $key);

Also note that the $key in this context comes from the original array, not the one with all the keys to be removed.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top