簡體   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