Álvaro N. Franz
Álvaro N. Franz

Reputation: 1228

Pick a random key of an array but forcing one of the values

Let's suppose I have an array of arrays:

$A=array();
$A['lemonade']=array('a','b','g');
$A['tree']=array('a','b','f');
$A['willpower']=array('a','b','g');

How may i randomly grab one key of $A, but only of those containing 'g' in $A[n][2]?

The direct approach is to iterate though them all, create a new array containing only the arrays containing g, and then grabbing a random key in that new array.

$bro=array();
foreach($A as $k=>$hijito){
    if($hijito[2]=='g'){
        $bro[$k]=$hijito;
    }
}

$theKeyIWant=array_rand($bro);

But I wonder if there is some other fancier way to approach this.

Upvotes: 3

Views: 115

Answers (3)

mega6382
mega6382

Reputation: 9396

There is also this method using array_walk(DEMO):

$A = array();
$A['lemonade'] = array('a','b','g');
$A['tree'] = array('a','b','f');
$A['willpower'] = array('a','b','g');

$bro = $A;
array_walk($A, function($item, $key) use (&$bro)
{
    if($item[2] != 'g')
    {
        unset($bro[$key]);
    }
});

var_dump($bro);

Upvotes: 1

Chetan Ameta
Chetan Ameta

Reputation: 7896

try it with Array Iterator. have a look on below solution:

$n = 2; //key which need to be checked
$v = 'g'; //value which need to be checked
$key_array = array();
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($A));

foreach ($it as $key => $val) {
    $pkey = $it->getSubIterator($it->getDepth() - 1)->key(); //get parent key
    if($key == $n && $val == $v){
        $key_array[$pkey] = $A[$pkey];
    }
}
print_r($key_array); //desired array
print_r(array_rand($key_array)); //desired key

Upvotes: 1

Md. Sahadat Hossain
Md. Sahadat Hossain

Reputation: 3236

Try This. First I filter the array and then get random key.

$A=array();
$A['lemonade']=array('a','b','g');
$A['tree']=array('a','b','f');
$A['willpower']=array('a','b','g');

$theKey = array_rand($filteredArr = array_filter($A, function($arr){
    return ($arr[2] == 'g');
}));
echo $theKey;

Upvotes: 1

Related Questions