Last active
February 26, 2021 07:52
-
-
Save ibrahim-dogan/cc52c9aee281648be4ae1a3dd5995b0b to your computer and use it in GitHub Desktop.
compare two array of values (nested or not) and return only changed indexes as array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* It flattens multidimensional array to make arrays comparable | |
* then compares request with DB (usually) | |
* @param $request | |
* @param $toCompare | |
* @return array | |
* @example request: [["title" => "ABC"], ["title" => "DEF"]] | |
* toCompare: [["title" => "ABC"], ["title" => "XYZ"]] | |
* return: [1] (index 1 updated) | |
*/ | |
private function findUpdatedIndexes($request, $toCompare): array | |
{ | |
$flattenRequest = Arr::dot($request); | |
$flattenToCompare = Arr::dot($toCompare); | |
$updatedEntries = array_diff_assoc($flattenRequest, $flattenToCompare); | |
$updatedIndexes = []; | |
foreach ($updatedEntries as $key => $value) { | |
$index = explode(".", $key)[0]; | |
$updatedIndexes[] = $index; | |
} | |
return array_unique($updatedIndexes); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment