在第一个的基础上创建第二个 array_rand
Create a second array_rand based on the first
我的 array_rand 有问题。所以,我有一个像这样的 .yml :
discover:
first:
image: test1.jpg
second:
image: test2.jpg
third:
image: test3.jpg
现在在 php 中,我使用 array_rand 获取此图像,如下所示:
$firstKey = array_rand($aArray, 1);
$secondKey = array_rand($aArray, 1);
其中 $aArray 是一个数组 包含来自 .yml 的数组。
问题是当 $firstKey 和 $secondKey 相等时。这是一种删除 $firstKey 在创建第二个 array_rand 之前选择的密钥的方法吗?
我试过 unset:
unset($aArray['first']);
但是没有结果。
请帮帮我。提前致谢。
尝试以下:
$firstKey = array_rand($aArray, 1);
unset($aArray(array_keys($firstKey)[0]));
$secondKey = array_rand($aArray, 1);
如果您不想在 array_rand
的两次单独调用中获得重复的键,那么只需在一次调用中获得两个键:
$keys = array_rand($aArray, 2);
或者:
list($firstKey, $secondKey) = array_rand($aArray, 2);
摘自manual:
Parameters
array
The input array.
num
Specifies how many entries should be picked.
Return Values
When picking only one entry, array_rand()
returns the key for a random entry. Otherwise, an array of keys for the random entries is returned. This is done so that random keys can be picked from the array as well as random values. Trying to pick more elements than there are in the array will result in an E_WARNING
level error, and NULL
will be returned.
我的 array_rand 有问题。所以,我有一个像这样的 .yml :
discover:
first:
image: test1.jpg
second:
image: test2.jpg
third:
image: test3.jpg
现在在 php 中,我使用 array_rand 获取此图像,如下所示:
$firstKey = array_rand($aArray, 1);
$secondKey = array_rand($aArray, 1);
其中 $aArray 是一个数组 包含来自 .yml 的数组。 问题是当 $firstKey 和 $secondKey 相等时。这是一种删除 $firstKey 在创建第二个 array_rand 之前选择的密钥的方法吗? 我试过 unset:
unset($aArray['first']);
但是没有结果。 请帮帮我。提前致谢。
尝试以下:
$firstKey = array_rand($aArray, 1);
unset($aArray(array_keys($firstKey)[0]));
$secondKey = array_rand($aArray, 1);
如果您不想在 array_rand
的两次单独调用中获得重复的键,那么只需在一次调用中获得两个键:
$keys = array_rand($aArray, 2);
或者:
list($firstKey, $secondKey) = array_rand($aArray, 2);
摘自manual:
Parameters
array
The input array.
num
Specifies how many entries should be picked.
Return Values
When picking only one entry,
array_rand()
returns the key for a random entry. Otherwise, an array of keys for the random entries is returned. This is done so that random keys can be picked from the array as well as random values. Trying to pick more elements than there are in the array will result in anE_WARNING
level error, andNULL
will be returned.