比较两个数组并使用php取消数组中的任何匹配对?

时间:2017-02-21 23:48:47

标签: php arrays multidimensional-array compare

我对数组和多维数组很新,我想知道如何比较两个数组的key =>值对(或者包含数组的两个不同键的单个数组?)并取消设置key =>每个数组中与键和值匹配的值。

示例数组:

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] => test@group.com
        )

)

因此,from是基本键数组,to是比较键数组。 我想遍历tofrom个键组,找到匹配的键,并比较两个匹配项的值。

如果key =>值对匹配,则取消设置tofrom键阵列中的key =>值。

如果to中找到的密钥不在from中,请将其保留在to数组中。但是,如果在from中找不到to中找不到的密钥,请将其从from密钥数组中取消设置。

将上述数组转换为:

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

    [to] => Array
        (
            [group_name] => test adgroup
            [zone_id] => 2
            [group_email] => test@group.com
        )

)

1 个答案:

答案 0 :(得分:1)

@Meta尝试以下概念:

<?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" => "test@group.com"
                    )

            );

    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