从in_array语句

时间:2016-02-17 22:57:05

标签: php mysql arrays

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

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

现在,在while循环中,如果我的变量$ number等于'raffle_ticket_num',我会检查$ ticket中的所有数组。我使用以下代码(来自@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的回复更新帖子

2 个答案:

答案 0 :(得分:2)

版本1 foreach见@FuzzyTree的答案

版本2 array_filter

$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);
    }
}

答案 1 :(得分:1)

如果您需要打印匹配的user_idticket_id,请使用foreach逐个检查每个故障单,当您看到匹配#的故障单时,您可以打印其他细节

foreach($tickets as $ticket) {
    if($ticket['raffle_ticket_num'] == $number) {
        print 'In array';
        print $ticket['user_id'];
        print $ticket['ticket_id'];
        //break; //uncomment if you just want one
    }
}