在 php 二维数组中打印随机结果
print random result in php 2 dimensional array
对于一个简单的数组,我可以使用以下代码打印一个随机项目:
$key = array_rand($arr);
$value = $arr[$key];
但我需要用二维数组和一个条件来完成。
我有一个这样的数组
$arr = array ( 'news' => 'text1',
'news' => 'text2',
'fun' => 'text3',
'news' => 'text4',
'echo' => 'text5',
'fun' => 'text6');
我想要 php
中类似这个算法的东西
if($type == 'news')
print random($arr($type));
所以结果是:
text1 or text2 or text4
或另一个例子:
if($type == 'fun')
print random($arr($type));
results: text3 or text6
但是我该怎么做呢?
正如@rizier123指出的:
You can't have multiple keys with the same name!! Every though about
how you identify each value if there would be multiple keys with the
same name?!
您的 $arr
键必须是唯一的,下面的代码反映了这一点。
/**
* multidimensional_array_rand()
*
* @param array $array
* @param integer $limit
* @return array
*/
function multidimensional_array_rand( $array, $limit ) {
uksort( $array, 'callback_rand' );
return array_slice( $array, 0, $limit, true );
}
/**
* callback_rand()
*
* @return bool
*/
function callback_rand() {
return rand() > rand();
}
即:
$arr = array ( 'news1' => 'text1',
'news2' => 'text2',
'fun' => 'text3',
'news4' => 'text4',
'echo' => 'text5',
'fun' => 'text6');
print_r( multidimensional_array_rand( $arr, 1 ) );
输出:
Array
(
[news4] => text4
)
演示:
对于一个简单的数组,我可以使用以下代码打印一个随机项目:
$key = array_rand($arr);
$value = $arr[$key];
但我需要用二维数组和一个条件来完成。
我有一个这样的数组
$arr = array ( 'news' => 'text1',
'news' => 'text2',
'fun' => 'text3',
'news' => 'text4',
'echo' => 'text5',
'fun' => 'text6');
我想要 php
中类似这个算法的东西if($type == 'news')
print random($arr($type));
所以结果是:
text1 or text2 or text4
或另一个例子:
if($type == 'fun')
print random($arr($type));
results: text3 or text6
但是我该怎么做呢?
正如@rizier123指出的:
You can't have multiple keys with the same name!! Every though about how you identify each value if there would be multiple keys with the same name?!
您的 $arr
键必须是唯一的,下面的代码反映了这一点。
/**
* multidimensional_array_rand()
*
* @param array $array
* @param integer $limit
* @return array
*/
function multidimensional_array_rand( $array, $limit ) {
uksort( $array, 'callback_rand' );
return array_slice( $array, 0, $limit, true );
}
/**
* callback_rand()
*
* @return bool
*/
function callback_rand() {
return rand() > rand();
}
即:
$arr = array ( 'news1' => 'text1',
'news2' => 'text2',
'fun' => 'text3',
'news4' => 'text4',
'echo' => 'text5',
'fun' => 'text6');
print_r( multidimensional_array_rand( $arr, 1 ) );
输出:
Array
(
[news4] => text4
)
演示: