<?php
/**
* Diffs two datasets of lists and performs basic sanity checks.
*
* @param array $dataset1 The first dataset (array of lists).
* @param array $dataset2 The second dataset (array of lists).
* @return array An array containing the diff results, including:
* - 'added': Lists present in $dataset2 but not in $dataset1.
* - 'removed': Lists present in $dataset1 but not in $dataset2.
* - 'modified': Lists present in both datasets but with differences.
* - 'errors': Any errors encountered during the comparison.
*/
function diffDatasets(array $dataset1, array $dataset2): array
{
$added = [];
$removed = [];
$modified = [];
$errors = [];
// Helper function to compare two lists
function compareLists(array $list1, array $list2): array
{
$diff = [];
$len1 = count($list1);
$len2 = count($list2);
$minLen = min($len1, $len2);
for ($i = 0; $i < $minLen; $i++) {
if ($list1[$i] !== $list2[$i]) {
$diff[] = ['index' => $i, 'value1' => $list1[$i], 'value2' => $list2[$i]];
}
}
if ($len1 > $len2) {
for ($i = $minLen; $i < $len1; $i++) {
$diff[] = ['index' => $i, 'value1' => $list1[$i], 'value2' => null];
}
} elseif ($len2 > $len1) {
for ($i = $minLen; $i < $len2; $i++) {
$diff[] = ['index' => $i, 'value1' => null, 'value2' => $list2[$i]];
}
}
return $diff;
}
// Check if datasets are arrays
if (!is_array($dataset1) || !is_array($dataset2)) {
$errors[] = ['type' => 'invalid_input', 'message' => 'Datasets must be arrays.'];
return ['added' => [], 'removed' => [], 'modified' => [], 'errors' => $errors];
}
// Iterate through the first dataset
foreach ($dataset1 as $list1) {
$found = false;
foreach ($dataset2 as $list2) {
if ($list1 === $list2) {
$found = true;
break;
}
}
if (!$found) {
$removed[] = $list1;
}
}
// Iterate through the second dataset
foreach ($dataset2 as $list2) {
$found = false;
foreach ($dataset1 as $list1) {
if ($list1 === $list2) {
$found = true;
break;
}
}
if (!$found) {
$added[] = $list2;
}
}
// Find modified lists
foreach ($dataset1 as $list1) {
foreach ($dataset2 as $list2) {
if ($list1 === $list2) {
$modified[] = compareLists($list1, $list2);
break;
}
}
}
return [
'added' => $added,
'removed' => $removed,
'modified' => $modified,
'errors' => $errors,
];
}
/**
* Example Usage
*/
/*
$dataset1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
$dataset2 = [[1, 2, 3], [4, 5, 7], [10, 11, 12]];
$diff = diffDatasets($dataset1, $dataset2);
print_r($diff);
*/
?>
Add your comment