简体   繁体   中英

Find missing elements from array based on another (keys not values)

I need to test an array to make sure it has all elements I am expecing. The twist here is that we are talking about multidimensional arrays. Here is an example:

$required_data = [

    'firstname',
    'lastname',
    'shipping' => [

        'address',
        'city',
        'contacts' => [

            'phone',
            'email'
        ]
    ]
];

$incoming_data = [

    'firstname' => 'Mike',
    'shipping' => [

        'address' => '1st Avenue',
        'contacts' => [

            'phone',
            'email' => 'test@example.com'
        ]
    ]
];

I simply need to detect the two missing elements ( lastname and city ). I don't care about values. I test them separately.

At the moment I'm playing with this function just to get true when all required elements are provided or false otherwise.

It works when $incoming_data doesn't have any value but as soon as I start adding values (eg. Mike , 1st Avenue etc.) it fails.

function validate($incoming_data, $required_data)
{
    foreach ($required as $key => $value) {

        if (!isset($data[$key])) {

            return false;
        }

        if (is_array($data[$key]) && false === validate($data[$key], $value)) {

            return false;
        }
    }

    return true;
}

I can't understand where my function starts playing with values. All is see are comparisons based on keys. Whut?

Thanks.

you have to set empty data in your $required_data tab like so:

$required_data = [
        'firstname' => '',
        'lastname' => '',
        'shipping' => [
            'address' => '',
            'city' => '',
            'contacts' => [
                'phone',
                'email'
            ]
        ]
    ];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM