我有两个随机数组,我需要在第二个数组中搜索第一个数组中的数字,如果匹配则用css改变它们的颜色,将它们标记为匹配。把它想象成一个彩票号码检查器。
我是用很长时间的方式完成的,但我想知道是否有办法缩短编码时间。
$white_balls = range(1, 70);
shuffle($white_balls);
$white_balls = array_slice($white_balls, 0, 5);
$five_ball = range(1, 70);
shuffle($five_ball);
$five_ball = array_slice($five_ball, 0, 5);
if(in_array($five_ball[0], $white_balls)) {
echo '<span style="color:red;">'.$five_ball[0].'</span>, ';
}else { echo $five_ball[0].", ";
}
if(in_array($five_ball[1], $white_balls)) {
echo '<span style="color:red;">'.$five_ball[1].'</span>, ';
}else { echo $five_ball[1].", ";
}
if(in_array($five_ball[2], $white_balls)) {
echo '<span style="color:red;">'.$five_ball[2].'</span>, ';
}else { echo $five_ball[2].", ";
}
if(in_array($five_ball[3], $white_balls)) {
echo '<span style="color:red;">'.$five_ball[3].'</span>, ';
}else { echo $five_ball[3].", ";
}
if(in_array($five_ball[4], $white_balls)) {
echo '<span style="color:red;">'.$five_ball[4].'</span>, ';
}else { echo $five_ball[4]." - ";
}
答案 0 :(得分:1)
<?php
function draw_balls($draw_count, $total_balls) {
$balls = range(1, $total_balls);
shuffle($balls);
return array_slice($balls, 0, $draw_count);
}
$one = draw_balls(5, 10);
$two = draw_balls(5, 10);
foreach($two as $num)
$out[] = in_array($num, $one)
? '<span style="color:red;">' . $num . '</span>'
: $num;
print implode(', ', $out);
此外:
$winning_balls = array_intersect($two, $one);
printf('Summary: %d out of %d balls are winners.',
count($winning_balls),
count($two)
);