Last active
August 22, 2019 03:13
-
-
Save adamcrampton/9f6d9168f1978871c94527baf55bff03 to your computer and use it in GitHub Desktop.
Loops through a nested array and adds a hash key for each data set
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 | |
/** | |
* Generates a hash for each nested array in the data set. | |
* Sets itself as the parent key - useful for comparisons. | |
* | |
* @param array $dataArray | |
* @param array $preserveFields Fields to return but not include in hash | |
* @return array $updatedArray | |
*/ | |
private function setHashKeys(array $dataArray, array $preserveFields = []) | |
{ | |
$updatedArray = []; | |
foreach($dataArray as $item => $arrayValues) { | |
// Create temporary array with only the items we need. | |
$tempArray = []; | |
$tempArray['part_id'] = $arrayValues['part_id']; | |
$tempArray['code'] = $arrayValues['code']; | |
$tempArray['price'] = floatval($arrayValues['price']); | |
// Add hash key. | |
$arrayHash = md5(serialize($tempArray)); | |
// Add values to new array. | |
$updatedArray[$arrayHash] = $tempArray; | |
// Add back preserved fields. | |
foreach ($preserveFields as $field) { | |
$updatedArray[$arrayHash][$field] = $dataArray[$item][$field]; | |
} | |
} | |
return $updatedArray; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment