Thursday, 30 August 2018

PHP Compare two multidimensional tables

I have two multidimensional arrays like this: Guest allow array

Array
(
    [0] => 5
    [1] => 2
    [2] => 3
)

and second one like this
   Array
(
    [0] => Array
        (
            [property_id] => 6
            [guest_allow] => 2
        )

    [1] => Array
        (
            [property_id] => 9
            [guest_allow] => 3
        )

    [2] => Array
        (
            [property_id] => 62
            [guest_allow] => 2
        )

    [3] => Array
        (
            [property_id] => 72
            [guest_allow] => 3
        )

    [4] => Array
        (
            [property_id] => 76
            [guest_allow] => 4
        )

    [5] => Array
        (
            [property_id] => 80
            [guest_allow] => 5
        )

    [6] => Array
        (
            [property_id] => 84
            [guest_allow] => 3
        )
)

So I have to match guest array all values are present in second array as well as I have to check guest values is less than to second array of guest_allow. If there is not match single value return empty array. If match value so return only match value. I want return array like this:
       Array
(
    [0] => Array
        (
            [property_id] => 6
            [guest_allow] => 2
        )

    [1] => Array
        (
            [property_id] => 9
            [guest_allow] => 3
        )

    [2] => Array
        (
            [property_id] => 62
            [guest_allow] => 2
        )

    [3] => Array
        (
            [property_id] => 72
            [guest_allow] => 3
        )

    [4] => Array
        (
            [property_id] => 84
            [guest_allow] => 3
        )
    [5] => Array
        (
            [property_id] => 76
            [guest_allow] => 4
        )
)

Is it possible return this type array? Thanks.

Assuming that $guestArr is your guest array and $secondArr is your second array, the solution would be like this:
foreach($secondArr as $key => $arr){
    if(!in_array($arr['guest_allow'], $guestArr)){
        unset($secondArr[$key]);
    }
}

// display $secondArr array
var_dump($secondArr);

Here's the live demo.

0 comments:

Post a Comment