Meta
Meta

Reputation: 1860

compare two arrays and unset any matching pairs from the arrays with php?

I am pretty new with arrays and multi-dimensional arrays, and am wondering how to go about comparing the key=>value pairs of two arrays (or a single array with two different keys that contain arrays?) and unset the key=>value pairings from each array that match keys and value.

Example Array:

Array
(
    [from] => Array
        (
            [active] => 1
            [airport_ids] => 
            [group_name] => test adgrp
            [zone_id] => 12
            [creation_time] => 1234567890
        )

    [to] => Array
        (
            [active] => 1
            [airport_ids] => 
            [group_name] => test adgroup
            [zone_id] => 2
            [group_email] => [email protected]
        )

)

So, from is the base key array and to is the comparison key array. I want to iterate through both to and from key arrays, finding matching keys, and comparing the values of the two matches.

If they key=>value pair matches, unset the key=>value from both to and from key arrays.

if there is a key found in to that is not in from, leave it in the to array. However, if there is a key found in from that is not found in to, unset it from the from key array.

Turning the above array into something like this:

Array
(
    [from] => Array
        (
            [group_name] => test adgrp
            [zone_id] => 12
        )

    [to] => Array
        (
            [group_name] => test adgroup
            [zone_id] => 2
            [group_email] => [email protected]
        )

)

Upvotes: 0

Views: 1049

Answers (1)

lazyCoder
lazyCoder

Reputation: 2561

@Meta try this below concept:

<?php
    $arr1 = 
            array
            (
                "from" => array
                    (
                        "active" => 1,
                        "airport_ids" => null,
                        "group_name" => "test adgrp",
                        "zone_id" => 12,
                        "creation_time" => 1234567890
                    ),

                "to" => array
                    (
                        "active" => 1,
                        "airport_ids" => null,
                        "group_name" => "test adgroup",
                        "zone_id" => 2,
                        "group_email" => "[email protected]"
                    )

            );

    echo "<pre>";
    print_r($arr1); //before

    foreach($arr1["from"] as $key => $value) {
      foreach($arr1["to"] as $key1 => $value1) {
        if($key == $key1 && $value == $value1){
            unset($arr1["from"][$key], $arr1["to"][$key1]);
            break;
        }

      }
    }
    echo "<pre>";
    print_r($arr1); //after

Upvotes: 1

Related Questions