mercredi 4 août 2021

Generating one random string from multiple arrays in same function

I'm new with PHP and working on a code generator (found on here) that fires when placing an order in woocommerce.

That's working fine when generating from a set of characters:

function generateRandomString($length = 9) {
    $characters = 'ABC';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

I'm having trouble figuring out array_rand and using it to generate a string from multiple arrays in the same function. Trying to select one option from each array and string them together with a space in-between

function generateRandomString($length = 9) {
    $arr11 = array( "a"=>"1x0",
                    "b"=>"1x1",
                    "c"=>"1x2" );
    $arr12 = array( "d"=>"1y3",
                    "e"=>"1y4",
                    "f"=>"1y5" );        
    $arr13 = array( "g"=>"1z6",
                    "h"=>"1z7",
                    "i"=>"1z8" );
    $arr21 = array( "j"=>"2x9",
                    "k"=>"2x10",
                    "l"=>"2x11" );        
    $arr22 = array( "m"=>"2y12",
                    "n"=>"2y13",
                    "o"=>"2y14" );
    $arr23 = array( "p"=>"2x15",
                    "q"=>"2z16",
                    "r"=>"2z17" );
    $arr31 = array( "s"=>"3z18",
                    "t"=>"3x19",
                    "u"=>"3x20" );
    $arr32 = array( "v"=>"3y21",
                    "w"=>"3y22",   
                    "x"=>"3y23" );
    $arr33 = array( "y"=>"3z24",
                    "z"=>"3z25",
                    "0"=>"3z26" );

    $randomString = array_rand($arr11, $arr12, $arr13, $arr21, $arr22, $arr23, $arr31, $arr32, $arr33);
    return $randomString;
}


add_action( 'woocommerce_add_order_item_meta', 'add_order_item_meta', 10, 9 );
function add_order_item_meta($item_id, $values) {
    $random_number = randomString(9);;
    wc_update_order_item_meta($item_id, 'Choices', $random_number);
}

add_action( 'woocommerce_before_single_product_summary', 'lottery_display_tickets', 9 );

function lottery_display_tickets() {
 print_r(get_field('random_number'));
}

I know above code is blatantly wrong I'm really not sure what I'm doing. Appreciate any help!




Aucun commentaire:

Enregistrer un commentaire