dougutuo9879 2013-04-17 14:29
浏览 44
已采纳

PHP数组键和值的比较

I have two arrays that I am trying to find the differences / similarities between the two.

Here is the arrays:

   [781]=>
   array(7) {
     ["Pri_ID"]=>
     string(3) "781"
     ["Type"]=>
     string(7) "Athlete"
     ["EntryDate"]=>
     string(10) "2013-04-15"
     ["Status"]=>
     string(6) "Active"
     }
    [782]=>
    array(7) {
    ["Pri_ID"]=>
    string(3) "782"
    ["EntryDate"]=>
    string(10) "2013-04-15"
    ["Status"]=>
    string(7) "Removed"
    }

here is the second array:

      [780]=>
      array(7) {
      ["Pri_ID"]=>
      string(3) "781"
      ["EntryDate"]=>
      string(10) "2013-04-15"
      ["Status"]=>
      string(7) "Removed"
      }
      [782]=>
      array(7) {
      ["Pri_ID"]=>
      string(3) "782"
      ["EntryDate"]=>
      string(10) "2013-04-15"
      ["Status"]=>
      string(7) "Active"
      }

Notice that the key in the second array (780 ) does not exist in the first array. Also notice that the 'status' of array number two (id 782 )is now 'active' but was originally in a status of removed.

The overall goal of this project is to compare the two arrays, located any differences, then placed these differences in either and array or a string and email the differences. Here is what I have tried so far:

$Deleted[] = array_diff_assoc($myarrayOld, $myarrayNew);
$Added[] = array_diff_assoc($myarrayNew, $myarrayOld); 

This will pick up the changes between the array keys, but not the statuskeys of the array.

  • 写回答

2条回答 默认 最新

  • dougang1605 2013-04-17 14:37
    关注

    Use an recursive function like this

    function array_diff_assoc_recursive($array1, $array2) {
        $difference=array();
        foreach($array1 as $key => $value) {
            if( is_array($value) ) {
                if( !isset($array2[$key]) || !is_array($array2[$key]) ) {
                    $difference[$key] = $value;
                } else {
                    $new_diff = array_diff_assoc_recursive($value, $array2[$key]);
                    if( !empty($new_diff) )
                        $difference[$key] = $new_diff;
                }
            } else if( !array_key_exists($key,$array2) || $array2[$key] !== $value ) {
                $difference[$key] = $value;
            }
        }
        return $difference;
    }
    

    Reference: PHP documentation

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟