简体   繁体   中英

Help with php random random array

I need help with an array problem I have, so far I have this:

$array1 = array('foo1', 'foo2', 'foo3', 'foo4', 'foo5');

$array2 = array('newfoo1', 'newfoo2', 'newfoo3', 'newfoo4', 'newfoo5');

$random1 = array_rand($array2);
$random2 = $array2[$random1];

foreach($array1 as $key){
 echo $key . '<br />';
 echo $random2 . '<br /><br />';
}

which outputs:

foo1
newfoo4

foo2
newfoo4

foo3
newfoo4

foo4
newfoo4

foo5
newfoo4

But I want "newfoo4" (array2) to be a random item so it would output somethng like this:

foo1
newfoo3

foo2
newfoo4

foo3
newfoo1

foo4
newfoo5

foo5
newfoo2

rather then the same,

BUT also allow duplicates of array2 so array1 and array2 do not have to have the same amount items in their arrays ....

so for instance if array1 had 5 items and array 2 only 3 items end result output could be:

foo1
newfoo3

foo2
newfoo1

foo3
newfoo3

foo4
newfoo2

foo5
newfoo3

...I hope this makes sense to someone ...

$array1 = array('foo1', 'foo2', 'foo3', 'foo4', 'foo5');
$array2 = array('newfoo1', 'newfoo2', 'newfoo3', 'newfoo4', 'newfoo5');

foreach($array1 as $key){
    echo $key . '<br />';
    echo $array2[array_rand($array2)] . '<br /><br />';
}

Try putting this line

$random2 = $array2[array_rand($array2)];

into your foreach loop, like so:

foreach($array1 as $key){
    $random2 = $array2[array_rand($array2)];
    echo $key . '<br />';
    echo $random2 . '<br /><br />';
}

How about something like this?

foreach($array1 as $key){
 $rand_num = rand(0, count($array2));
 echo $key . '<br />';
 echo $array2[$rand_num] . '<br /><br />';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM