问题描述
我在一个循环中内爆数组中的连续单词(相对于索引号)
$array=array(
1=>array('First','word'),5=>array('Second',6=>array('Third',7=>array('-','non-word'),8=>array('Fourth',10=>array('Fifth','word')
);
$prev=-1;
$results=array();
foreach($array as $key=>$v){
$value=$v[0];
$type=$v[1];
if($key==$prev+1){ // check if the index is successive
$results[]=$value; // possibly $results=array('value'=>$value,'type'=>$type);
}else{
echo implode(' ',$results).PHP_EOL; // HERE is the question
$results=array($value);
}
$prev=$key;
}
echo implode(' ',$results).PHP_EOL; // echoing remaining $result
我的问题是我不知道如何实现 non-word
的条件(例如,连字符、/ 等)。
在上面的示例中,$value
、if($type=='non-word')
周围不应有空格。
预期的输出是
First
Second Third-Fourth
Fifth
总的来说,我想找到一种方法来合并类型的条件(例如,如果它在组的开头或结尾,则省略 non-word
)。
解决方法
我只是在学习正则表达式,但这种方法似乎有效,尽管不可否认它并不漂亮 - 在数组中标记您的非单词,以便在事后很容易用 preg_replace
替换它们
$array=array(
1=>array('First','word'),5=>array('Second',6=>array('Third',7=>array('-','non-word'),8=>array('Fourth',10=>array('Fifth','word')
);
$prev=-1;
$results=array();
foreach($array as $key=>$v){
$type=$v[1];
$value= $type=="non-word" ? "%%".$v[0]."%%" : $v[0];
if($key==$prev+1){ // check if the index is successive
$results[]=$value; // possibly $results=array('value'=>$value,'type'=>$type);
}else{
$output = implode(' ',$results); // HERE is the question
$output = preg_replace("/ %%(.*?)%% /","$1",$output);
echo $output.PHP_EOL;
$results=array($value);
}
$prev=$key;
}
实际效果如下:https://www.tehplayground.com/wmPSi5wP6eLcBAdk
,遍历每一项,并输出它,那么需要做的就是:
- 检查下一个值是否连续,如果:
- 否:添加新行。
- 是:and 是一个词,current 不是一个非词,加一个空格。
<?php
$array=array(
1=>array('First','word')
);
foreach ($array as $key => $value) {
echo $value[0];
if (!isset($array[$key+1])) {
echo PHP_EOL;
} else if($array[$key+1][1] === 'word' && $array[$key][1] !== 'non-word') {
echo ' ';
}
}
结果:
First
Second Third-Fourth
Fifth