我有以下代码
$allArray = array("AAAAA","ABBB","BBBB","BDDFD","TTTT","ZZZZ");
当每个字符串的第一个字符发生变化时,我需要做什么,然后我必须对其进行一些字体更改。
foreach($allArray as $data){
$first = substr($data,0,1);
// HOW TO COMPARE FIRST WITH OTHER VALUES & IF A IS CHANGED FROM B,T or Z THEN I HAVE TO MAKE THAT FIRST CHARACTER COLOR CHANGE & INCREASE THE SIZE OF FONT.
}
我需要输出如下
AAAAA ABBBB
BBBB BDDFD
TTT
ZZZZ
所以所有的alphabates都在不同的组中。
该字符串的第一个字符,颜色和颜色不同。不同的大小。
所以
BBBB BDDFD
这里来自BBBB - >第一个B将采用不同的颜色和不同大小
答案 0 :(得分:1)
您可以使用数组键通过$your_array[$current_key-1]
:
$allArray = array("AAAAA","ABBB","BBBB","BDDFD","TTTT","ZZZZ");
sort($allArray);
$color = rand_color(); // initial
$break = ' ';
foreach($allArray as $k => $value) {
if($k == 0) { // initial
echo "<span style='color: $color; font-size: 35px;'>$value[0]</span>" . substr($value, 1);
continue;
}
if($allArray[$k-1][0] != $value[0]) {
$color = rand_color(); // generate new row
$break = '<br/>';
$value = "<span style='color: $color; font-size: 35px;'>$value[0]</span>" . substr($value, 1);
} else {
$break = ' '; // continuation
}
echo "$break $value";
}
function rand_color() { // this is just for presentational purposes
return sprintf('#%06X', mt_rand(0, 0xFFFFFF));
}
另一种方法是使用hashmap,然后在收集后显示它:
$allArray = array("AAAAA","ABBB","BBBB","BDDFD","TTTT","ZZZZ");
$group = array();
foreach ($allArray as $value) {
$group[$value[0]][] = $value;
}
foreach($group as $values) {
$values = implode(' ', $values);
$color = rand_color();
$values = "<span style='color: $color; font-size: 35px;'>$values[0]</span>" . substr($values, 1) . '<br/>';
echo $values;
}
function rand_color() {
return sprintf('#%06X', mt_rand(0, 0xFFFFFF));
}
答案 1 :(得分:0)
foreach($allArray as $data => $value){
$first = substr($value,0,1);
}
$data
只有数组的索引而不是值。值为$value
,因此将与$value
进行比较。
答案 2 :(得分:-1)
嗯试试这个
foreach($allArray as $data => $value){
$first = substr($value,0,1);
$newString = "<span color='red'>$firts</span>".substr($value,1,strlen($value));
}