Search code examples
phpmultidimensional-arrayarray-difference

array_diff with calculation


Please, consider the following arrays:

$reference = array(
    '080604' => 4,
    '080703' => 4,
    '080734' => 2,
    '080819' => 2,
    '088341' => 2,
    '805238' => 20,
    '805283' => 4,
    '805290' => 2,
    '805849' => 2,
    '806051' => 2,
    '806068' => 2,
);

$test = array(
    '080604' => 2,
    '080703' => 4,
    '080819' => 1,
    '088341' => 2,
    '805238' => 20,
    '805283' => 4,
    '805290' => 2,
    '805849' => 2,
    '806051' => 2,
    '806068' => 2,
);

They are quite similar, but can have some various differences, e.g. it's possible that: - some keys of $reference are not present in $test at all - some keys of $test are not present in $reference at all - all keys are present, but the values in $reference and $test are different (sometimes $reference value is bigger than $test and sometimes the value of $test is bigger than $reference)

I need to find out the differences automatically and to output them in a way, that not only the difference in count itself, but also a description is provided, e.g.

$result = [
   '080604' => [
       'reference' => 4,
       'test' => 2
   ]
];

If some value is in only one of the lists:

$result = [
   '1234567890' => [
       'reference' => 0,
       'test' => 2
   ]
];

or something like that.

Does someone have an idea, which is the best way to accomplish this in an elegant way? Thank you very much!


Solution

  • Iterate over each and populate the array with values if present:

    $combined = [];
    
    foreach ($reference as $key => $val) {
        $combined[$key] = [
            'test' => 0,
            'reference' => $val,
        ];
    }
    
    foreach ($test as $key => $val) {
        if (!isset($combined[$key])) {
            $combined[$key] = [
                'reference' => 0,
                'test' => 0,
            ]
        }
    
        $combined[$key]['test'] = $val;
    }
    

    $combined will contain both values from both arrays with reference to both the elements from $reference and $test.