Occasionally, I find I need to sort some objects, grouping them by multiple values. I usually accomplish this by concatenating the values together, with an underscore or other delineator in between, and then use that as an array index.
// group all objects with a common parent_id, date, and type
foreach ($objects as $obj) {
$hash = $obj->parent_id . '_' . $obj->date . '_' . $obj->type;
$sorted_objects[$hash][] = $obj;
}
...ick! There's got to be a better way than abusing PHP's loose typing and string concatenation. Is there any way to perform a hash on multiple values? It seems I should be able to just do something like this:
$hash = sha1_multiple($obj->parent-id, $obj->date, $obj->type);
Am I already using the best method, or is there a better way?
Using PHP's serialization makes it a bit neater, but less efficient:
function sha1_multiple() {
$args = func_get_args();
return sha1(serialize($args));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With