首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > PHP >

数组随机取值。解决方案

2012-05-08 
数组随机取值。PHP code$json EOT[{album:album1,truck:truck1},{album:album1,truck:

数组随机取值。

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 />';} 

热点排行