Comparing Array Structures using a Recursive Diff Algorithm
Question:
How can you generate a recursive diff of two arrays, where matching elements are marked green and non-matching elements are marked red?
Answer:
To perform a recursive diff, which compares arrays recursively, you can utilize a custom function like the one described in the comments of the PHP array_diff function:
function arrayRecursiveDiff($aArray1, $aArray2) { $aReturn = array(); foreach ($aArray1 as $mKey => $mValue) { if (array_key_exists($mKey, $aArray2)) { if (is_array($mValue)) { $aRecursiveDiff = arrayRecursiveDiff($mValue, $aArray2[$mKey]); if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; } } else { if ($mValue != $aArray2[$mKey]) { $aReturn[$mKey] = $mValue; } } } else { $aReturn[$mKey] = $mValue; } } return $aReturn; }
This function iterates through the keys and values of the first array, checks if the key exists in the second array, and handles the comparison based on the data type. If there is a structural or value mismatch, the result is added to the $aReturn array.
Benefits of Recursive Diff:
Implementation Considerations:
以上が色分けされた違いを持つ配列構造の再帰的差分を作成するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。