簡體   English   中英

PHP,如何生成唯一數字列表?

[英]PHP, how can I produce a list of unique numbers?

我有一些數字將成為sql查詢的一部分,像這樣...

152258, 152258, 152258, 152258, 152261, 152261, 152261, 152261, 152261, 152270, 
152270, 152270, 152287, 152287, 152287, 152287

我的查詢非常復雜,列表很長,我需要生成一個唯一的數字列表,我可以使用正則表達式來做到這一點嗎?

如果沒有怎么辦?

這是使字符串具有唯一數字的方法: http : //codepad.org/cziNtZOS

<?php

$myString = "152258,152258,152258,152258,152261,152261,152261,152261,152261,152270,152270,152270,152287,152287,152287,152287";
$array = explode(",",$myString);
$unique = array_unique ( $array  );
$myUniqueString = implode(",",$unique);
echo $myUniqueString ;
?>

我本打算為您編寫一個函數,結果PHP已經有了一個函數: array_unique()

編輯 :無論如何,這是替代方法之一:

function uniquify_array($a)
{
    $b = array();  // I wish I could write just $b = {};
    foreach ($a as $i)
        $b[$i] = $i;
    return $b;
}

請注意,此函數僅適用於值,而內置的array_unique()將鍵保留在原始數組中。

如果您需要一定范圍的數字,請使用PHP的range()方法

如果您想要唯一的數字列表,則可以使用PHP的rand()方法

range(): http//php.net/manual/en/function.range.php

rand(): http//php.net/manual/en/function.rand.php

編輯正如@RobertPitt所指出的,uniqid也可以用於生成ID: http ://php.net/manual/en/function.uniqid.php

生成一組數字,然后只使用array_unique函數

$nums = array();

for ($i = 0; $i < $limit; $i++) { $nums[] = rand() * 10000;

$nums = array_unique($nums);

}

蘇丹

使用RANGE()

參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM