Reputation: 281
I have an array filled with the result of a query which is as follows:
$ticket[] = array(
'ticket_id' => $row->ticket_id,
'user_id' => $row->user_id,
'raffle_ticket_num' => $row->raffle_ticket_num
);
Now, in a while loop, I check in all arrays inside $tickets if my variable $number equals 'raffle_ticket_num'. I do this with the following code (from @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++;
}
The problem that I'm having now is that because I'm using a foreach loop, if more than one results are found, it causes it to echo each result as much as there are rows in $ticket[]... So with 2 rows it echos everything 2 times (because of the foreach). Does anyone know a solution or alternatives for this?
You can see it live here: http://tinyurl.com/hxbhx7y .The bold numbers are slot 21 and 38 which are taken and showing the user_id (1). But as you can see it shows each number 2 times (because foreach has 2 results)
EDIT: Post updated with @Fuzzy Tree's answer
Upvotes: 1
Views: 60
Reputation: 3144
Version 1
foreach
see answer by @FuzzyTree
Version 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));
So best and easiest way to do it prepare your tickets array outside of raffles loop. Solution
<?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);
}
}
Upvotes: 2
Reputation: 32402
If you need to print the matching user_id
and ticket_id
then use a foreach
to check each ticket one by one and when you see a ticket with the matching #, you can print the other details
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
}
}
Upvotes: 1