Skip to content

Instantly share code, notes, and snippets.

@adamcrampton
Last active August 22, 2019 03:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamcrampton/9f6d9168f1978871c94527baf55bff03 to your computer and use it in GitHub Desktop.
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
<?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