gpt4 book ai didi

php - 从 in_array 语句获取值

转载 作者:行者123 更新时间:2023-11-29 05:14:08 24 4
gpt4 key购买 nike

我有一个数组,其中填充了如下查询结果:

$ticket[] = array( 
'ticket_id' => $row->ticket_id,
'user_id' => $row->user_id,
'raffle_ticket_num' => $row->raffle_ticket_num
);

现在,在 while 循环中,如果我的变量 $number 等于“raffle_ticket_num”,我将检查 $tickets 中的所有数组。我使用以下代码(来自@Fuzzy Tree)执行此操作:

$ticket_num=1;

while ($ticket_num <= $total_slots){

foreach($ticket as $test) {
if($test['raffle_ticket_num'] == $ticket_num) {
echo $ticket_num.' claimed by '.$test['user_id'];
}

else{
echo $ticket_num;
}

}

$ticket_num++;
}

我现在遇到的问题是,因为我使用的是 foreach 循环,如果找到多个结果,它会根据 $ticket[] 中的行数来回显每个结果。 . 因此,对于 2 行,它会回显所有内容 2 次(因为 foreach)。有谁知道这个的解决方案或替代方案?

你可以在这里看到它:http://tinyurl.com/hxbhx7y .粗体数字是插槽 21 和 38,它们被占用并显示 user_id (1)。但正如您所见,它显示每个数字 2 次(因为 foreach 有 2 个结果)

编辑:使用@Fuzzy Tree 的回答更新帖子

最佳答案

版本 1foreach 查看@FuzzyTree 的回答

版本 2数组过滤器

$number = 1;
$winners = array_filter($tickets, function ($ticket) use ($number) {
return $ticket['raffle_ticket_num'] == $number;
});

// $winners now has all winning tickets.
var_dump($winners);

// Bonus pick a random winner
shuffle($winners);
var_dump(current($winners));

最好和最简单的方法是在抽奖循环之外准备您的门票阵列。解决方案

<?php

$tickets[] = array(
'ticket_id' => 1,
'user_id' => 2,
'raffle_ticket_num' => 15
);

$tickets[] = array(
'ticket_id' => 2,
'user_id' => 2,
'raffle_ticket_num' => 25
);

$tickets[] = array(
'ticket_id' => 3,
'user_id' => 1,
'raffle_ticket_num' => 21
);

$raffles = range(1, 50);

// Preparing tickets array. Now when I think Flattened is not the best word to describe it :)
$ticketsFlattened = array();
foreach ($tickets as $ticket) {
$ticketsFlattened[$ticket['raffle_ticket_num']] = $ticket;
}

// Could be while if you want
foreach ($raffles as $number) {
if (array_key_exists($number, $ticketsFlattened)) {
echo sprintf(
"Ticket %s is clamed by %s, ticket id %s %s",
$number,
$ticketsFlattened[$number]['user_id'],
$ticketsFlattened[$number]['ticket_id'],
PHP_EOL
);

} else {
echo sprintf("Ticket %s unclaimed %s", $number, PHP_EOL);
}
}

关于php - 从 in_array 语句获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35469449/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com