如何从多维数组中获取随机数据?

时间:2016-08-31 03:59:10

标签: php arrays

是否可以从数组中获取随机数据?

请参阅我的数组:

    
Array
(
    [0] => Array
        (
            [0] => My Data
            [1] => Airport
            [2] => Md
        )

    [1] => Array
        (
            [0] => Live in fear
            [1] => Science
            [2] => Sc
        )

    [2] => Array
        (
            [0] => State History
            [1] => Government
            [2] => MP
        )

    [3] => Array
        (
            [0] => Real Estate
            [1] => Other
            [2] => Property
        )

    [4] => Array
        (
            [0] => Real State
            [1] => Not Sure
            [2] => NoData
        )
)

我需要这种随机输出...

Array
(
    [0] => Array
        (
            [0] => My Data
            [1] => Airport
            [2] => Md
        )

    [1] => Array
        (
            [0] => Real State
            [1] => Not Sure
            [2] => NoData
        )

    [2] => Array
        (
            [0] => My Data
            [1] => Airport
            [2] => Md
        )

    [3] => Array
        (
            [0] => State History
            [1] => Government
            [2] => MP

        )

    [4] => Array
        (
            [0] => Live in fear
            [1] => Science
            [2] => Sc

        )
)

3 个答案:

答案 0 :(得分:0)

您只需使用and this

即可
  

bool shuffle(array& $ array)

     

此函数将数组随机化(随机化元素的顺序)。它使用的伪随机数生成器不适合加密目的。

shuffle($array); // Shuffles your array keys randomly every time.

答案 1 :(得分:0)

  

shuffle()将是从多维数组中获取随机值的更好选择。

参考:http://php.net/manual/en/function.shuffle.php

shuffle()示例:

shuffle()函数随机化数组中元素的顺序。

此函数为数组中的元素指定新键。现有密钥将被删除

<?php
$my_array = array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow","e"=>"purple");

shuffle($my_array);
print_r($my_array);
?> 

<强>输出:

Array ( [0] => red [1] => yellow [2] => green [3] => blue [4] => purple )
//The Output will keep shuffling if you refresh the browser.

答案 2 :(得分:0)

尝试以下的随机播放功能。希望它可以帮到你。

function shuffle_assoc($list) { 
  if (!is_array($list)) return $list; 

  $keys = array_keys($list); 
  shuffle($keys); 
  $random = array(); 
  foreach ($keys as $key) { 
    $random[] = $list[$key]; 
  }
  return $random; 
} 

$arr = array();
$arr[] = array('id' => 50, 'foo' => 'hello');
$arr[] = array('id' => 17, 'foo' => 'byebye');
$arr[] = array('id' => 19, 'foo' => 'foo');

print_r(shuffle_assoc($arr));