通过数组中的键选择多个随机值 [英] Select multiple random values by key from arrays

查看:76
本文介绍了通过数组中的键选择多个随机值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从阵列中选择5个随机ID。这是我的数组 $ test

I want to select 5 random ID's from the arrays. Here is my array $test:

Array
(
    [id] => 13
    [pets] => 8
)
Array
(
    [id] => 15
    [pets] => 8
)
Array
(
    [id] => 16
    [pets] => 10
)
Array
(
    [id] => 17
    [pets] => 9
)
Array
(
    [id] => 18
    [pets] => 10
)
Array
(
    [id] => 19
    [pets] => 10
)
Array
(
    [id] => 20
    [pets] => 0
)
Array
(
    [id] => 21
    [pets] => 8
)
Array
(
    [id] => 22
    [pets] => 9
)
Array
(
    [id] => 23
    [pets] => 4
)
Array
(
    [id] => 24
    [pets] => 0
)
Array
(
    [id] => 40
    [pets] => 8
)
Array
(
    [id] => 43
    [pets] => 2
)

如何从数组中选择5个随机ID,并将其放入这样的字符串中:

How can I select 5 random ID's from the array and put them into a string like this:

$ids = '13,17,18,21,43';

我尝试使用 array_rand ,但是它似乎不适用于我的数组类型。我不确定是否有其他内置的PHP函数可以完成这种工作,或者我是否必须创建自己的函数,最好有这样的函数插入数字。谢谢

I've tried to use array_rand but it does not seem to work for my type of arrays. i'm not sure if there are any other built in PHP functions that can do this type of job or if I have to create my own function, It would be nice to have my own function like this to plug in the numbers. thanks

推荐答案

首先通过<$提取索引 id 列的索引c $ c> id ,然后随机选择5个,最后分解为一个逗号分隔的列表。由于键必须是唯一的,所以这样做的好处是,如果数组中恰好有重复项,则不返回重复的 id s:

First extract the id column indexing also by the id, then pick 5 random ones, and finally implode into a comma separated list. Since keys must be unique, this has the added benefit of not returning duplicate ids if there happen to be duplicates in the array:

$ids = implode(',', array_rand(array_column($test, 'id', 'id'), 5));

对于功能:

function array_rand_multi($array, $key, $num) {
    return implode(',', array_rand(array_column($array, $key, $key), $num));
}

这篇关于通过数组中的键选择多个随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆