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 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址