繁体   English   中英

如何从php数组生成一个唯一的字符串

[英]How to produce a unique string from a php array

我需要一个来自数组的唯一字符串,以便我可以在不测量该数组的输入的情况下判断它何时发生变化。 我正在尝试计算一个计算值而不是添加代码以查找数组中的更改的计算效率。 数组本身可以有各种各样的值,为了将来打样,我不想尝试测量是否已将新值添加到数组中,我更愿意创建一些字符串或散列,如果数组本身会改变变化。

例如:

$a = Array(
'var1' => 1,
'var2' => 2,
'var3' => 3,
);

如果我使用md5(http_build_query($a))或许添加了ksort来确认密钥的顺序没有改变,那么可能会生成一个唯一的字符串,我可以用来与另一个应用程序的运行进行比较评估阵列是否已更改。

我正在寻找替代的,可能更快或更优雅的解决方案。

我为此使用md5(serialize($array)) 它更好,因为适用于多维数组。

PHP有一个array_diff()函数,不知道它对你有用。

否则,你可以最终使用php提供的增量散列可能性: http ://www.php.net/manual/en/function.hash-init.php迭代遍历数组的每个值并将它们添加到增量散列中。

感谢所有的想法。

我已经尝试了所有这些,除了我的服务器没有安装的sha-256。

结果如下:

Average (http_build_query): 1.3954045954045E-5
Average (diff): 0.00011533766233766
Average (serialize): 1.7588411588412E-5
Average (md5): 1.6036963036966E-5
Average (implode-haval160,4): 1.5349650349649E-5

这是运行1000次并平均结果的操作。 刷新几次后,我可以看出http_build_query是最快的。 我想我的下一个问题是,如果有人能想到使用这种方法的任何陷阱吗?

谢谢

这是我的代码:

class a {

    static $input;

    function test() {
        $start = null;
        $s = $e = $d = $g = $h = $i = $k = array();
        self::$input = array();

        for ($x = 0; $x <= 30; $x++) {
            self::$input['variable_' . $x] = rand();
        }

        for ($x = 0; $x <= 1000; $x++) {
            $start = microtime();

            $c = http_build_query(self::$input);
            ($c == $c);

            $s[] = microtime() - $start;
        }

        for ($x = 0; $x <= 1000; $x++) {
            $start = microtime();

            $c = md5(http_build_query(self::$input));
            ($c == $c);

            $e[] = microtime() - $start;
        }

        for ($x = 0; $x <= 1000; $x++) {
            $start = microtime();

            $c = array_diff(self::$input, self::$input);

            $d[] = microtime() - $start;
        }
        for ($x = 0; $x <= 1000; $x++) {
            $start = microtime();

            $c = serialize(self::$input);
            ($c == $c);

            $g[] = microtime() - $start;
        }

        for ($x = 0; $x <= 1000; $x++) {
            $start = microtime();

            $c =  hash("haval160,4", implode(',',self::$input));
            ($c == $c);

            $h[] = microtime() - $start;
        }
        echo "<pre>";

//print_r($s);
        echo "Average (http_build_query): " . array_sum($s) / count($s) . "<br>";
        echo "Average (diff): " . array_sum($d) / count($d) . "<br>";
        echo "Average (serialize): " . array_sum($g) / count($g) . "<br>";
        echo "Average (md5): " . array_sum($e) / count($e). "<br>";
        echo "Average (implode-haval160,4): " . array_sum($h) / count($h);
    }

}

a::test();

你可以随时做

$str = implode(",", $a);
$check = hash("sha-256", $str);

从理论上讲,它应该检测数组大小,数据或排序的变化。

当然,你可以使用你想要的任何哈希。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM