0

I am looking forward to compare two arrays in PHP.

For example, I have array A:

Array
(
    [0] => Array
        (
            [option_id] => 19
            [sub_option_id] => 57
        )

    [1] => Array
        (
            [option_id] => 1093
            [sub_option_id] => 3582
        )

    [2] => Array
        (
            [option_id] => 1093
            [sub_option_id] => 57
        )

)

And array B:

Array
(
    [0] => Array
        (
            [order_option_detail] => Array
                (
                    [0] => Array
                        (
                            [option_id] => 19
                            [sub_option_id] => 57
                        )

                    [1] => Array
                        (
                            [option_id] => 1093
                            [sub_option_id] => 57
                        )

                    [2] => Array
                        (
                            [option_id] => 1093
                            [sub_option_id] => 3582
                        )

                )

        )

    [1] => Array
        (
            [order_option_detail] => Array
                (
                    [0] => Array
                        (
                            [option_id] => 1
                            [sub_option_id] => 2
                        )

                )

        )

)

By looking at the data structure, I can see that array B contains array A. How can I achieve the same analysis using PHP, ie how to check array B contain array A?

Please help me if you know! Thank you so much!

dWinder
  • 11,597
  • 3
  • 24
  • 39
justcntt
  • 197
  • 1
  • 2
  • 12

2 Answers2

0

From arrayB you only need 'order_option_detail'.

So if we use array_column we can get those isolated.

$details = array_column($arrayB, 'order_option_detail');
foreach($details as $detail){ // loop the two items.
    if($detail === $arrayA){
        // Do something
    }
}

https://3v4l.org/TW670

Andreas
  • 23,610
  • 6
  • 30
  • 62
0

You can use the following function for array compare:

function array_equal($a, $b) {
    if (!is_array($a) || !is_array($b) || count($a) != count($b))
        return false;
    $a = array_map("json_encode", $a);
    $b = array_map("json_encode", $b);
    return array_diff($a, $b) === array_diff($b, $a); // mean both the same values
}

And then use it as:

$details = array_column($arrayB, 'order_option_detail');
foreach($details as $detail){ // loop the two items.
    if (array_equal($detail, $arrayA)) {
       // Do what ever
    }
}
dWinder
  • 11,597
  • 3
  • 24
  • 39