在PHP数组中内爆相邻元素(按索引)
我在循环中内爆数组中的连续字(相对于索引号)在PHP数组中内爆相邻元素(按索引),php,foreach,implode,Php,Foreach,Implode,我在循环中内爆数组中的连续字(相对于索引号) $array=array( 1=>array('First','word'), 5=>array('Second','word'), 6=>array('Third','word'), 7=>array('-','non-word'), 8=>array('Fourth','word'), 10=>array('Fifth','word') ); $prev=-1;
$array=array(
1=>array('First','word'),
5=>array('Second','word'),
6=>array('Third','word'),
7=>array('-','non-word'),
8=>array('Fourth','word'),
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
我的问题是,我不知道如何实现非单词的条件(例如连字符、/)
在上面的示例中,$value
,if($type=='non-word')
周围应该没有空格
预期输出为
First
Second Third-Fourth
Fifth
一般来说,我想找到一种方法来合并类型的条件(例如,如果是在组的开头或结尾,则省略非单词)。我只是在学习正则表达式,但这种方法似乎有效,尽管不可否认,这并不漂亮-在数组中标记非单词,以便在事件发生后用
preg\u replace
轻松替换它们
$array=array(
1=>array('First','word'),
5=>array('Second','word'),
6=>array('Third','word'),
7=>array('-','non-word'),
8=>array('Fourth','word'),
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;
}
这就是它的作用:在每个项目上循环并输出它,然后需要做的就是:
- 检查下一个值是否连续,如果:
- 否:添加新行
- 是:and是一个单词,current不是非单词,请添加空格
我确实想过使用正则表达式来修改输出,但它需要定义所有非单词。在您的情况下(定义单词字符),如果单词是由非ASCII字母数字组成的,则不起作用。一般来说,在循环中提供时使用
$type
比在输出中猜测更容易。不确定$type是什么意思,但我确实修改了我的答案,以便在数组中也有一个显式选项(搜索所有空格
字符空格),第二列是值的类型(单词或非单词)。问题是有一长串非单词字符。例如,您的代码不适用于测试-再次抱歉@Googlebot-我不知怎么看错了问题。我更新了答案,好奇这是否有用。干杯这是个聪明的主意!
<?php
$array=array(
1=>array('First','word'),
5=>array('Second','word'),
6=>array('Third','word'),
7=>array('-','non-word'),
8=>array('Fourth','word'),
10=>array('Fifth','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