배열에서 임의의 값을 얻는 방법?
라는 배열이 있습니다 $ran = array(1,2,3,4);
이 배열에서 임의의 값을 가져 와서 변수에 저장해야합니다. 어떻게 할 수 있습니까?
당신은 또한 할 수 있습니다 :
$k = array_rand($array);
$v = $array[$k];
이것은 연관 배열이있을 때 수행하는 방법입니다.
PHP는 다음과 같은 기능을 제공합니다. array_rand ()
http://php.net/manual/en/function.array-rand.php
$ran = array(1,2,3,4);
$randomElement = $ran[array_rand($ran, 1)];
mt_rand ()를 사용할 수 있습니다
$random = $ran[mt_rand(0, count($ran) - 1)];
값이 필요한 경우 기능으로도 유용합니다.
function random_value($array, $default=null)
{
$k = mt_rand(0, count($array) - 1);
return isset($array[$k])? $array[$k]: $default;
}
$value = $array[array_rand($array)];
array_rand 함수를 사용하여 아래와 같이 배열에서 임의의 키를 선택할 수 있습니다.
$array = array("one", "two", "three", "four", "five", "six");
echo $array[array_rand($array, 1)];
rand 및 count 함수를 사용하여 임의의 인덱스를 선택할 수 있습니다.
$array = array("one", "two", "three", "four", "five", "six");
echo $array[rand(0, count($array) - 1)];
라 라벨에서 파생 됨 Collection::random()
:
function array_random($array, $amount = 1)
{
$keys = array_rand($array, $amount);
if ($amount == 1) {
return $array[$keys];
}
$results = [];
foreach ($keys as $key) {
$results[] = $array[$key];
}
return $results;
}
용법:
$items = ['foo', 'bar', 'baz', 'lorem'=>'ipsum'];
array_random($items); // 'bar'
array_random($items, 2); // ['foo', 'ipsum']
몇 가지 참고 사항 :
$amount
보다 작거나 같아야합니다count($array)
.array_rand()
doesn't shuffle keys (since PHP 5.2.10, see 48224), so your picked items will always be in original order. Useshuffle()
afterwards if needed.
Documentation: array_rand()
, shuffle()
edit: The Laravel function has noticeably grown since then, see Laravel 5.4's Arr::random()
. Here is something more elaborate, derived from the grown-up Laravel function:
function array_random($array, $number = null)
{
$requested = ($number === null) ? 1 : $number;
$count = count($array);
if ($requested > $count) {
throw new \RangeException(
"You requested {$requested} items, but there are only {$count} items available."
);
}
if ($number === null) {
return $array[array_rand($array)];
}
if ((int) $number === 0) {
return [];
}
$keys = (array) array_rand($array, $number);
$results = [];
foreach ($keys as $key) {
$results[] = $array[$key];
}
return $results;
}
A few highlights:
- Throw exception if there are not enough items available
array_random($array, 1)
returns an array of one item (#19826)- Support value "0" for the number of items (#20439)
The array_rand
function seems to have an uneven distribution on large arrays, not every array item is equally likely to get picked. Using shuffle on the array and then taking the first element doesn't have this problem:
$myArray = array(1, 2, 3, 4, 5);
// Random shuffle
shuffle($myArray);
// First element is random now
$randomValue = $myArray[0];
Another approach through flipping array to get direct value.
Snippet
$array = [ 'Name1' => 'John', 'Name2' => 'Jane', 'Name3' => 'Jonny' ];
$val = array_rand(array_flip($array));
array_rand
return key not value. So, we're flipping value as key.
Note: PHP key alway be an unique key, so when array is flipped, duplicate value as a key will be overwritten.
$rand = rand(1,4);
or, for arrays specifically:
$array = array('a value', 'another value', 'just some value', 'not some value');
$rand = $array[ rand(0, count($array)-1) ];
Does your selection have any security implications? If so, use random_int()
and array_keys()
. (random_bytes()
is PHP 7 only, but there is a polyfill for PHP 5).
function random_index(array $source)
{
$max = count($source) - 1;
$r = random_int(0, $max);
$k = array_keys($source);
return $k[$r];
}
Usage:
$array = [
'apple' => 1234,
'boy' => 2345,
'cat' => 3456,
'dog' => 4567,
'echo' => 5678,
'fortune' => 6789
];
$i = random_index($array);
var_dump([$i, $array[$i]]);
Demo: https://3v4l.org/1joB1
Use rand() to get random number to echo random key. In ex: 0 - 3
$ran = array(1,2,3,4);
echo $ran[rand(0,3)];
In my case, I have to get 2 values what are objects. I share this simple solution.
$ran = array("a","b","c","d");
$ranval = array_map(function($i) use($ran){return $ran[$i];},array_rand($ran,2));
I'm basing my answer off of @ÓlafurWaage's function. I tried to use it but was running into reference issues when I had tried to modify the return object. I updated his function to pass and return by reference. The new function is:
function &random_value(&$array, $default=null)
{
$k = mt_rand(0, count($array) - 1);
if (isset($array[$k])) {
return $array[$k];
} else {
return $default;
}
}
For more context, see my question over at Passing/Returning references to object + changing object is not working
One line: $ran[rand(0, count($ran) - 1)]
This will work nicely with in-line arrays. Plus, I think things are tidier and more reusable when wrapped up in a function.
function array_rand_value($a) {
return $a[array_rand($a)];
}
Usage:
array_rand_value(array("a", "b", "c", "d"));
On PHP < 7.1.0, array_rand()
uses rand()
, so you wouldn't want to this function for anything related to security or cryptography. On PHP 7.1.0+, use this function without concern since rand()
has been aliased to mt_rand()
.
You get a random number out of an array as follows:
$randomValue = array_rand($rand,1);
참고URL : https://stackoverflow.com/questions/1643431/how-to-get-random-value-out-of-an-array
'Programing' 카테고리의 다른 글
Swift Xcode 6에서 버튼 텍스트를 변경하는 방법은 무엇입니까? (0) | 2020.07.28 |
---|---|
jQuery UI-외부를 클릭하면 대화 상자 닫기 (0) | 2020.07.28 |
jQuery 및 CSS-표시 제거 / 추가 : 없음 (0) | 2020.07.28 |
htaccess 액세스 제어 허용 원본 (0) | 2020.07.28 |
Windows 및 Mac OS 모두에서 Python의 기본 OS 응용 프로그램으로 문서 열기 (0) | 2020.07.28 |