Search code examples
phparraysmultidimensional-arrayarray-difference

Array Comparison in Php, and find the diff in values


I want to compare two arrays in php. My arrays looks like this

Array ( 
[0] => Array ( [Id] => 1 [row1] => 1458)
[1] => Array ( [Id] => 2 [row1] => 16) 
[2] => Array ( [Id] => 3 [row1] => 115) 
[3] => Array ( [Id] => 4 [row1] => 18) 
[4] => Array ( [Id] => 5 [row1] => 13) 
[5] => Array ( [Id] => 6 [row1] => 13) 
[6] => Array ( [Id] => 7 [row1] => 131)
)

Array ( 
[0] => Array ( [Id] => 1 [row1] => 158)
[1] => Array ( [Id] => 2 [row1] => 165) 
[2] => Array ( [Id] => 3 [row1] => 111) 
[3] => Array ( [Id] => 4 [row1] => 186) 
[4] => Array ( [Id] => 5 [row1] => 3)
)

Firstly, array1 size and array2 sizes were not equal always. Id value in array1 may or may not present in array2, If the value is not present, function have to print the total index in array3, like

[someindex] => Array ( [Id] => 6 [row1] => 13 )

if it is present, function should subtract the row1 of array1 to row1 of array2 and print in array3, like this

[someindex] => Array ( [Id] => 1 [row1] => 1300)

and my final output should be,

Array ( 
[0] => Array ( [Id] => 1 [row1] => 1300)
[1] => Array ( [Id] => 2 [row1] => -149) 
[2] => Array ( [Id] => 3 [row1] => 4) 
[3] => Array ( [Id] => 4 [row1] => -168) 
[4] => Array ( [Id] => 5 [row1] => 10) 
[5] => Array ( [Id] => 6 [row1] => 13) 
[6] => Array ( [Id] => 7 [row1] => 131)
)

Can any one help me in solving this problem.


Solution

  • First, you either have to make the second array searchable by using the Id value as the keys or write a search function. I'm choosing the former:

    $searchable = array_reduce($array2, function(&$result, $item) {
        return $result + array($item['Id'] => $item['row1']);
    }, array());
    

    The array_reduce() function starts with an empty array and builds it using the array addition operator; this creates an array that can be dereferenced using the id.

    Then you perform a map operation on the first array:

    $array3 = array_map(function($item) use ($searchable) {
        $value = isset($searchable[$item['Id']]) ? $searchable[$item['Id']] : 0;
        $item['row1'] -= $value;
    //    $item['row2'] = $item['row1'] - $value;
        return $item;
    }, $array1);
    

    Doing a map operation preserves the original array and creates a new one with the values you choose inside a callback function.