【码】PHP严格比对两个数组键和值
in 代码片段 with 0 comment

【码】PHP严格比对两个数组键和值

in 代码片段 with 0 comment

代码来源:自己整理编写
说明:用PHP严格比较两个数组之间的差异,连数据类型都要比较。

<?php
    //二维数组解决方案
    function checkData( $XMLData=[], $otherData=[], &$XMLDiff=[], &$otherDiff=[], &$field) {
        $k = 'id';
        $XMLMap = [];
        foreach ( $XMLData as $value ){
            $XMLMap[$k] = $value;
        }

        foreach ($otherData as $value){
            $_otherDiff = []; $_XMLDiff = [];
            compareArr($value, $XMLMap[$k], $_otherDiff, $_XMLDiff);
            if( $_otherDiff ){
                array_push($otherDiff, $value);
                array_push($XMLDiff, $XMLMap[$k]);
                array_push($field, array_keys($_otherDiff));
            }
        }
    }

/**
 * 严格比对两个一维数组之间键和值的差异。
 * @param array $dataOne  一维数组
 * @param array $dataTwo  一维数组
 * @param array $oneDiff  数组一所独有的键值对
 * @param array $twoDiff  数组二所独有的键值对
 */
function compareArr( $dataOne=[], $dataTwo=[], &$oneDiff=[], &$twoDiff=[] ){
    foreach ( $dataOne as $key => $value ) {
        if( !isset($dataTwo[$key]) || $dataTwo[$key] !== $value ){
            $oneDiff[$key] = $value;
            $twoDiff[$key] = $dataTwo[$key];
        }
    }
}
Comments are closed.