好的抱歉生病了重写这个,因为我试图使用一个简化的例子,但我相信它更复杂所以我试图让所有符合某个标准的用户,然后把它们放在一个数组中,之后洗牌顺序和将用户放在数组块中。
从那里我做了一个if / else语句,说明每个块是否已满,是否有ID,但我无法获取ID:
//Get all users who are eligable
$eligable_users = get_users('meta_key=eligable&meta_value=1');
//Set all eligable users into an array
$eligable_user_array = array();
foreach ( $eligable_users as $users ) {
$eligable_user_array[] = $users;
}
//Shuffle users among arrays
shuffle($eligable_user_array);
//Change this to adjust chunk size
$winning_array_chunk_size = 2;
//Create array chunks
$array_chunk = array_chunk($eligable_user_array , $winning_array_chunk_size , false);
//Foreach array chunk
foreach($array_chunk as $individual_winner_chunk) {
//If a chunk isnt filled igonre
if( sizeof($individual_winner_chunk) < $winning_array_chunk_size) {
//Users in this chunk arnt entered into prize draw
}
//For each filled chunk get a user
else{
//print_r($individual_winner_chunk);
//Get randomised users from each chunk
$random_user_from_chunk = array_rand($individual_winner_chunk , 1);
foreach($random_user_from_chunk as $userchunk){
echo $userchunk->data->ID;
}
}
这是不正确输出的部分:
echo $ userchunk-&gt; data-&gt; ID;
答案 0 :(得分:1)
您正在错误地使用array_rand函数。
array_rand返回随机密钥。 点击此处查看更多信息:http://php.net/manual/en/function.array-rand.php
因此,如果您只需要一个密钥,请执行以下操作:
$random_user_from_chunk = array_rand($individual_winner_chunk , 1);
echo $individual_winner_chunk[$random_user_from_chunk]->data->ID;
如果您需要更多随机用户,请增加array_rand中的number选项
$random_user_from_chunk = array_rand($individual_winner_chunk , 2);
echo $individual_winner_chunk[$random_user_from_chunk[0]]->data->ID
echo $individual_winner_chunk[$random_user_from_chunk[1]]->data->ID
答案 1 :(得分:-1)
如果从JSON中获取$userlist
值,则只需将对象更改为关联数组即可:
$random_user = array_rand(json_decode($userlist, TRUE), 1);
然后您可以访问:
foreach($random_user as $individual_user) {
echo $individual_user['data']['ID'];
}