I want to be able to remove elements from the multidimentianal array by key
Example of such an array can be:
Array
(
[data] => Array
(
[todo] => code review
[schedule] => Array
(
[endDate] => 2019-05-10T00:00:00+01:00
[startDate] => 2019-05-09T00:00:00+01:00
)
[codeDetails] => Array
(
[language] => PHP
[type] => class
[abstract] => true
[methodCount] => Array
(
[public] => 3
[protected] =>
[private] => 1
)
[LOC] => 123
[cyclomaticComplexity] => 4
[author] => Array (
[name] => Lukasz
[email] => private@tulik.io
)
)
)
)
I have two methods, recursiveArrayDelete
removes any elements where the callback returns true
:
private function recursiveArrayDelete(array &$array, callable $callback): array
{
foreach ($array as $key => &$value) {
if (is_array($value)) {
$value = $this->recursiveArrayDelete($value, $callback);
}
if ($callback($value, $key)) {
unset($array[$key]);
}
}
return $array;
}
Second, removes properties all included in restrictedProperties
from the array
:
private function sanitizedArray(array &$array, array &$restrictedProperties): array
{
foreach ($restrictedProperties as $restrictedProperty) {
$this->recursiveArrayDelete(
$array,
static function () use ($array, $restrictedProperty): bool {
array_walk_recursive(
$array,
static function ($value, $key) use (&$bool, $restrictedProperty) {
// here $bool is as expected from condition
$bool = $key === $restrictedProperty;
});
// here is alwalys false
return $bool;
});
}
return $array;
}
Example of usage:
$this->sanitizedResponse($data, ['methodCount', `endDate`]);
Should remove these elements from array. But as I mentioned in commenrt sanitizedArray
where return $bool;
always result in false