PHP:比较两组数字,没有欺骗

发布于 2024-12-28 07:30:42 字数 250 浏览 0 评论 0原文

我正在为我的网站创建一个彩票竞赛,我需要知道比较数字的最简单方法,以便没有两个人可以选择相同的数字。它是7组数字,每个数字都是1到30之间的数字。

例如,如果用户1选择:1,7,9,17,22,25,29,我如何确保用户2不能选择这些相同的确切数字?

我正在考虑将所有 7 个数字放入一个数组中,对它进行排序,使数字按顺序排列,然后将它们连接成一个字符串。然后,当另一个用户选择他们的 7 个号码时,它会执行相同的操作,然后比较两个号码。有更好的方法吗?

I'm creating a lottery contest for my site, and I need to know the easiest way to compare numbers, so that no two people can choose the same numbers. It's 7 sets of numbers, each number is a number between 1 and 30.

For example, if user 1 chooses: 1, 7, 9, 17, 22, 25, 29 how can I make sure that user 2 can't choose those same exact number?

I was thinking about throwing all 7 numbers into an array, sort it so the numbers are in order, then join them into one string. Then when another user chooses their 7 numbers, it does the same, then compares the two. Is there a better way of doing it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

兮子 2025-01-04 07:30:42

你所描述的听起来对我来说是最好的方式,如果你正在同一个脚本中处理所有提交 - 我会trim(implode(',',$array)) 排序后的数组,将结果字符串存储在数组中,并调用 in_array() 来确定该值是否已存在。

但是我怀疑您实际上正在做的是将选择存储在数据库表中,并将以后的提交与该表进行比较。在这种情况下(我冒昧地假设这里使用 MySQL,但我想说它是 PHP 最常用的引擎)您应该创建一个包含 7 列 choice_1choice_2 ... choice_7(以及您想要的任何其他列)并在所有七个 choice_* 列中创建唯一索引。这意味着当您尝试插入重复行时,查询将失败。这让 MySQL 为您完成所有工作。

What you describe sounds like the best way to me, IF you are dealing with all submissions in the same script - I would trim(implode(',',$array)) the sorted array, store the resulting string in an array and call in_array() to determine whether the value already exists.

HOWEVER I suspect that what you are actually doing is storing the selections in a database table and comparing later submissions against this table. In this case (I am taking a liberty and assuming MySQL here but I would say it is the most common engine used with PHP) you should create a table with 7 columns choice_1, choice_2 ... choice_7(along with whatever other columns you want) and create a unique index across all seven choice_* columns. This means that when you try and insert a duplicate row, the query will fail. This lets MySQL do all the work for you.

以往的大感动 2025-01-04 07:30:42

尝试 array_diff。 php.net 上有一些非常好的示例。

Try array_diff. There are some really good examples on php.net.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文