日期:2014-05-17  浏览次数:20493 次

数组随机取值。
PHP code
$json = <<<EOT
[
{"album":"album1","truck":"truck1"},
{"album":"album1","truck":"truck3"},
{"album":"album1","truck":"truck4"},
{"album":"album1","truck":"truck6"},
{"album":"album2","truck":"truck2"},
{"album":"album2","truck":"truck3"},
{"album":"album3","truck":"truck2"},
{"album":"album3","truck":"truck5"}
{"album":"album4","truck":"truck5"},
{"album":"album4","truck":"truck6"},
{"album":"album5","truck":"truck1"},
{"album":"album5","truck":"truck3"},
{"album":"album6","truck":"truck2"},
{"album":"album6","truck":"truck3"},
{"album":"album6","truck":"truck4"},
{"album":"album7","truck":"truck2"},
{"album":"album7","truck":"truck5"},
{"album":"album7","truck":"truck6"}
]
EOT;
$data = json_decode($json);
foreach($data as $row){
   //echo '唱片:'.$row->album.' ,曲目:'.$row->truck.'<br />';
}



有一个json格式的数组。储存唱片专辑及曲目。
如何随机取出4个唱片,每个唱片取出一首曲目,且这4首曲目名不重复?(album为唱片,truck为曲目。)

------解决方案--------------------
我说错了,不是 array_rand 会出现重复项
而是他原始的数据有重复,需要做去重处理
PHP code
$data = json_decode($json);
foreach($data as $v) $r[$v->truck] = $v;
$data = $r;
$ar = array_rand($data, 4);
foreach($ar as $k) {
    echo '唱片:'.$data[$k]->album.' ,曲目:'.$data[$k]->truck.'<br />';
}