Ronnie Jespersen
Ronnie Jespersen

Reputation: 950

PHP check if some keys or values are in a multidimensional array

I have an array structure where I want to check if a key/value is present somewhere in the array. But I want to make the test in such a way that I make a an almost mirrored validation array.

Lets say I have a multidimensional array. This is the data I want to validate.

Array
(
[key1] => Array
    (
        [subkey1] => value
        [subkey2] => value
    )

[key2] => Array
    (
        [subkey3] => Array
            (
                [key1] => value
                [key2] => value
                [key3] => value
                [key4] => value
                [key5] => value
                [key6] => value
            )
    )
);

And this is the array of my keys and values that need to be present in the first array.

Array
(
[key1] => Array
    (
        [subkey2] => value
    )

[key2] => Array
    (
        [subkey3] => Array
            (
                [key5] => value
                [key6] => value
            )
    )
);

I cant compare the two arrays because they will never be the same. But I need to run through the data array somehow and validate up against the validation array. Both the key and value need to be at the right place and the key need the same name and the value should be the same as well. I'm just not sure how to make a decent check. Can I make some recursive check? Since some of the keys can be a value or another array it needs to check for this as well... that's why I'm thinking recursive but I'm not sure how to make that.

Hope you can help. Thanks.

Upvotes: 2

Views: 2418

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173572

You could use this to recursively determine whether all required keys are present:

function has_recursive($data, $required)
{
    foreach ($required as $key => $value) {
        if (!isset($data[$key])/* && $data[$key] === $value */) {
            return false;
        }
        if (is_array($data[$key]) && false === has_recursive($data[$key], $value)) {
            return false;
        }
    }
    return true;
}

has_recursive($data, $required); // false or true

Upvotes: 3

Voitcus
Voitcus

Reputation: 4446

I have not tested it so maybe this doesn't work (if so and this would be no help I will remove the answer).

First method is to check each key-value pairs recursively and then find what matches.

The second option can be that you recursively create flat key - value arrays using array_values() and array_keys(). I mean from something like

array(
  'subkey1' = array(
     'key1' = value1,
     'key2' = value2),
  'subkey2' = value3
)

You iteratively and recursive do

array(
  'key1' = value1,
  'key2' = value2,
  'subkey2' = value3
)

If you do this with both arrays being compared, you can find the matching key-value pairs using array_intersect_assoc().

This would however won't work if for example 'key1' == 'subkey2'.

Upvotes: 0

Related Questions