0

I've looked through articles and SO questions for the last hour and still can't find exactly what I'm looking for.

I have a single dimensional string array containing containing keys from my multidimensional array. Both arrays are dynamic. I need a way to remove every key in the 1D from the MD array.

It's hard to explain, so let me just show you.

$dynamicKeys = ['date', 'name', 'account'];

$arrayRequiringSanitization = [
  'name' => [
    'first' => 'Homer',
    'last' => 'simpson'
  ],
  'age' => 'unknown',
  'facts' => [
    'history' => [
      'date' => 'whenever',
      'occurred' => 'nope'
    ],
    'is' => 'existing'
  ]
];

function removeDynamicValues($arr, $vals) {
  // this is where i need help
}

The removeDynamicValues function should take the $arrayRequiringSanitization and $dynamicKeys and return an array that looks as follows:

$arrayRequiringSanitization = [
  'age' => 'unknown',
  'facts' => [
    'history' => [
      'occurred' => 'nope'
    ],
    'is' => 'existing'
  ]
];

So basically, it removed the name sub array and the date sub sub property. The important part is that both arrays are dynamic, and it's not known how deep $arrayRequiringSanitization will be nested.

Let me know if I need to provide further clarrification.

1
  • Using the technique from the duplicate: 3v4l.org/64P8a Commented Oct 27, 2020 at 13:38

1 Answer 1

1

You can do this quite easily with recursion. Here's the code.

/**
 * @param array<mixed> $arr initial array
 * @param array<string|int> $vals array of keys that need to be deleted
 * @return array<mixed>
 */
function removeDynamicValues(array $arr, array $vals): array
{
    $out = [];
    foreach ($arr as $key => $value) {
        if (!in_array($key, $vals, true)) {
            $out[$key] = is_array($value) ? removeDynamicValues($value, $vals) : $value;
        }
    }
    return $out;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.