PHP数组操作异常排查:程序错误还是环境问题?
文档分析程序问题汇总
背景与核心实现
我正在处理文档分析工作,构建了wordTree数组(每个元素格式为array(string, count),count代表该字符串在文档中的出现次数)。由于程序其他模块依赖wordTree的索引而非字符串副本,元素添加后不可移动;同时通过bTree存储索引,实现字符串的有序遍历与二分查找。
用于查找或添加字符串的PinWord函数代码如下:
function PinWord($word,&$wordTree,&$bTree,&$WTI) { global $BTreeA, $BTreeO; $F=0; $L=count($wordTree)-1; if (count($wordTree)!=count($bTree)) exit ("mismatch at L=$L"); // should never happen if ($L<0) {// first time through ($WTI=-1 initially) $wordTree[++$WTI]=array($word,1); $bTree[0]=0; return 0; } while ($F<=$L) {// do a binary search for the string $i=intval(($F+$L)/2); $j=$bTree[$i]; $test=$wordTree[$j][wv]; if ($word==$test) { $wordTree[$j][wc]++; // bump count return $j; } //found it if ($word<$test) $L=--$i; // change upper limit else $F=++$i; // change lower limit } $WTI=count($wordTree); // redundant if everything working $bt=array(); // going to rebuild $bTree foreach($wordTree as $k => $A) $bt[$A[wv]]=$k; if (count($wordTree)!=count($bt)) exit("duplicate words in word tree"); // shouldn't happen if (array_key_exists($word,$bt)) {//oops shouldn't happen Debug_M("misplaced key i=$i t=$bt[$word] key='$word'");// report error return $bt[$word];}// out of order, return anyway $bt[$word]=$WTI; ksort($bt);//sort strings in ascending order $bTree=array_values($bt);// replace $Btree $wordTree[]=array($word,1); if ($wordTree[$WTI][wv]!=$word) exit ("really bad, $word not same as ".$wordTree[$WTI][wv]."'"); if (count($wordTree)!=count($bTree)) exit ("mismatch B at $WTI"); return $WTI; }
核心问题
当前程序存在两个wordTree:一个仅存储纯英文字符串,运行逻辑正常;另一个仅存储非英文字符串,却出现bTree排序异常、重复字符串绕过array_key_exists检测的问题。
辅助优化疑问
ksort性能开销较大,能否通过array_slice、array_merge结合$word与$test优化排序逻辑?- 拆分
bTree(按首字符或字符串长度)是否能提升查找效率?
其他异常问题
str_replace替换连续换行符失效
以下代码处理制表符正常,但连续换行符时第二个换行符未正确替换:
$SC=array("\n","\t"); $SCA=array('n','t'); $z2=str_replace($SC,$SCA,$z);
本地与在线PHP字符串比较结果不一致
测试代码如下:
<?php $Left_W=array(' 12',' 13 ',' “4 ',' 2 ',' 2. ',' 3 ',' 3 ',' 4 ',' 5. ',' 6 '); $Right_W=array(' 12 ',' 13. ',' ',' 2. ',' 2',' 3',' 3. ',' 4. ',' 5 ',' 6. '); for ($i=0; $i<10; $i++) { $left=$Left_W[$i]; $right=$Right_W[$i]; if ($left<$right) $RO='<'; else $RO= '>'; echo "($i) '$left' $RO '$right'<br>";} ?>
在线编辑器输出符合预期,但本地Apache环境的PHP所有比较结果均为“<”,怀疑是PHP环境配置问题。
内容的提问来源于stack exchange,提问作者Howard Cary Morris
相关产品推荐
相关产品推荐

