mardi 16 juin 2015

Get random key from multidimensional array - weighted [duplicate]

This question already has an answer here:

I want to get a random key from a multidimensional array, but some keys have a higher weight than others. I can't find the answer to this in other questions here, because they are not suited for multidimensional arrays.

An example:

<?php
$random_values=array(
        1=>array(
            "title"=>"word",
            "description"=>"long text",
            "weight"=>"1"
        ),
        2=>array(
            "title"=>"word",
            "description"=>"long text",
            "weight"=>"5"
        ),
        3=>array(
            "title"=>"word",
            "description"=>"long text",
            "weight"=>"1"
        ),
        //and so on
    );
?>

How can I get a random key (1, 2 or 3)? The chance for key 2 is higher than for key 1 and key 3 because the weight is 5 instead of 1.

Thank you!




Aucun commentaire:

Enregistrer un commentaire