0
我想寫一個簡單的類來遞歸地從數組中刪除不需要的鍵。沒什麼特別的。遞歸從數組中刪除鍵的類方法
<?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類似,但我已經閱讀他們的答案,但沒有運氣。
謝謝。
多麼愚蠢的錯誤!謝謝!我已經失去了很多時間...... – Gianluca78