[英]How can I pull 3 unique values from a single array in PHP?
I have an array that I need to pull multiple values from but I can't have any of those values repeat. 我有一个数组,我需要从中提取多个值,但我不能重复任何这些值。
This is what I am doing now, but it does not discourage multiples of the same value. 这就是我现在正在执行的操作,但是它不会阻止相同值的倍数。
My array is: 我的数组是:
$boom = array("1", "2", "3", "4", "5", "6");
And I am using 3 of this code to pull the values: 我正在使用此代码中的3个来提取值:
echo $boom[array_rand($boom,1)];
The end result in the context of the page looks like this - "1, 4, 3" (or any variation of the numbers...) But my issue is that I have a need for the script to pull 3 non-repeating values. 页面上下文中的最终结果看起来像这样-“ 1、4、3”(或数字的任何变化...)但是我的问题是我需要脚本提取3个非重复值。
How can I do that? 我怎样才能做到这一点?
Use array_unique()
to get unique values then use shuffle()
to random the order. 使用
array_unique()
获得唯一值,然后使用shuffle()
随机排列顺序。 Then you can use array_slice()
to get the first three element and you can use implode()
to output them as a comma separated string. 然后,您可以使用
array_slice()
获取前三个元素,并可以使用implode()
将它们输出为逗号分隔的字符串。
$a = array_unique(array("1", "2", "3", "4", "5", "6"));
shuffle($a);
$b = array_slice($a, 0, 3);
echo implode(',', $b);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.