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");
$boom =数组(“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)];
echo $繁荣[用于($繁荣,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?
我怎么做呢?
1 个解决方案
#1
4
Use array_unique()
to get unique values then use shuffle()
to random the order. 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_unique()获取惟一值,然后使用shuffle()随机排序。然后可以使用array_slice()获取前三个元素,并可以使用内爆()将它们作为逗号分隔的字符串输出。
$a = array_unique(array("1", "2", "3", "4", "5", "6"));
shuffle($a);
$b = array_slice($a, 0, 3);
echo implode(',', $b);
演示
#1
4
Use array_unique()
to get unique values then use shuffle()
to random the order. 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_unique()获取惟一值,然后使用shuffle()随机排序。然后可以使用array_slice()获取前三个元素,并可以使用内爆()将它们作为逗号分隔的字符串输出。
$a = array_unique(array("1", "2", "3", "4", "5", "6"));
shuffle($a);
$b = array_slice($a, 0, 3);
echo implode(',', $b);
演示