mardi 8 janvier 2019

Add unique random value from array

I'm trying to generate a unique random value from an array and store it in another array so it can't be used again.

I've managed to generate the random value based on a meta field but I'm not sure how I would go about making this unique and ensuring the same values aren't being generated again. I've created an empty array $tickethistory to save the values into. Is it possible the next time it runs to run a validation check so the $lottery_max_tickets don't include the $tickethistory values?

I'm using the function below which returns the number and I', calling it when customers purchase a product in Woocommerce.

function add_lottery_ticket_number( $postid ) {

        $tickethistory = array();
        $lottery_max_tickets = get_post_meta( $postid, '_max_tickets', true );
        $max_tickets = range(1, $lottery_max_tickets);

        $ticketallocated = array_rand($max_tickets, 1);
        $tickethistory[] = $ticketallocated;

        return $ticketallocated;

}


for ( $i = 0; $i < $item_meta['_qty'][0]; $i++ ) {
                            add_post_meta( $product_id, '_participant_id', $order->get_user_id() );
                            $participants = get_post_meta( $product_id, '_lottery_participants_count', true ) ? get_post_meta( $product_id, '_lottery_participants_count', true ) : 0;
                            update_post_meta( $product_id, '_lottery_participants_count', intval( $participants ) + 1 );
                            $this->add_lottery_to_user_metafield( $product_id, $order->get_user_id() );
                            $ticketnumber = $this->add_lottery_ticket_number($product_id);
                            $log_ids[] = $this->log_participant( $product_id, $order->get_user_id(), $ticketnumber, $order_id, $item );
                        }




Aucun commentaire:

Enregistrer un commentaire