我的一些代码。。。
$a_array = array(2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 20);
$b_array = array(2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 20);
$a = $a_array[array_rand($a_array)];
$b = $b_array[array_rand($b_array)];
$a_multiples = array($a*1, $a*2, $a*3, $a*4, $a*5, $a*6, $a*7, $a*8, $a*9, $a*10);
$b_multiples = array($b*1, $b*2, $b*3, $b*4, $b*5, $b*6, $b*7, $b*8, $b*9, $b*10);
$result = array_intersect($a_multiples, $b_multiples);
$d = reset($result);
$d是$a和$b的LCM(假设它是$a与$b的前10倍)。然后我列出了a美元和b美元的前10个倍数。。。
echo $lista = implode(', ', $a_multiples);
echo $listb = implode(', ', $b_multiples);
如何在$lista和$listb中"突出显示"LCM(即粗体)?
如果您使用的是php 5.3或更高版本,您可以使用一个函数来创建一个可以传递到array_map:的highlighter(闭包)
function highlighterGenerator($lcd){
return function ($a) use ($lcd){
return $a == $lcd?"<strong>".$a."</strong>":$a;
}
}
使用:
echo implode(", ", array_map(highlighterGenerator($d), $a_multiples));
echo implode(", ", array_map(highlighterGenerator($d), $b_multiples));
对于php的旧版本,以下解决方案应该是等效的:
function highlighter($arr, $lcd){
$ret = array();
foreach($arr as $val){
$ret[] = $val == $lcd?"<strong>".$val."</strong>":$val;
}
return $ret;
}
使用:
echo implode(", ", highlighter($a_multiples, $d));
echo implode(", ", highlighter($b_multiples, $d));
试试这个(更快)
echo "<strong>" . implode("</strong><strong>", $a_multiples) . "</strong>";
echo "<strong>" . implode("</strong><strong>", $b_multiples) . "</strong>";
演示