PHP best way to MD5 multi-dimensional array?

后端 未结 13 2009
别那么骄傲
别那么骄傲 2020-12-07 11:48

What is the best way to generate an MD5 (or any other hash) of a multi-dimensional array?

I could easily write a loop which would traverse through each level of the

13条回答
  •  温柔的废话
    2020-12-07 12:33

    Currently the most up-voted answer md5(serialize($array)); doesn't work well with objects.

    Consider code:

     $a = array(new \stdClass());
     $b = array(new \stdClass());
    

    Even though arrays are different (they contain different objects), they have same hash when using md5(serialize($array));. So your hash is useless!

    To avoid that problem, you can replace objects with result of spl_object_hash() before serializing. You also should do it recursively if your array has multiple levels.

    Code below also sorts arrays by keys, as dotancohen have suggested.

    function replaceObjectsWithHashes(array $array)
    {
        foreach ($array as &$value) {
            if (is_array($value)) {
                $value = $this->replaceObjectsInArrayWithHashes($value);
            } elseif (is_object($value)) {
                $value = spl_object_hash($value);
            }
        }
        ksort($array);
        return $array;
    }
    

    Now you can use md5(serialize(replaceObjectsWithHashes($array))).

    (Note that the array in PHP is value type. So replaceObjectsWithHashes function DO NOT change original array.)

提交回复
热议问题