项目背景与OCR数据挑战
近期开发了一款视力筛查电子报告系统,旨在自动抓取验光过程中的屈光检查数据,并生成专业且易懂的电子报告,方便家长通过公众号或H5链接查看。
实现该功能的首要步骤是对纸质验光报告进行OCR识别。图片识别接口返回的数据结构为二维数组,原始报告样本如图所示:

OCR接口返回的具体数据结构如下所示:
array(3) {
["words_result"]=>
array(36) {
[0]=>
array(1) {
["words"]=>
string(8) "FA-6000A"
}
[1]=>
array(1) {
["words"]=>
string(10) "2026-09-16"
}
[2]=>
array(1) {
["words"]=>
string(7) "04:00"
}
[3]=>
array(1) {
["words"]=>
string(8) "SHOP:B"
}
[4]=>
array(1) {
["words"]=>
string(7) "NAME:"
}
[5]=>
array(1) {
["words"]=>
string(3) ""
}
[6]=>
array(1) {
["words"]=>
string(1) "C"
}
[7]=>
array(1) {
["words"]=>
string(1) "A"
}
[8]=>
array(1) {
["words"]=>
string(5) "-1.50"
}
[9]=>
array(1) {
["words"]=>
string(5) "-0.25"
}
[10]=>
array(1) {
["words"]=>
string(3) "131"
}
[11]=>
array(1) {
["words"]=>
string(5) "-1.50"
}
[12]=>
array(1) {
["words"]=>
string(7) "-0,25"
}
[13]=>
array(1) {
["words"]=>
string(3) "122"
}
[14]=>
array(1) {
["words"]=>
string(7) "-1,50"
}
[15]=>
array(1) {
["words"]=>
string(7) "-0,25"
}
[16]=>
array(1) {
["words"]=>
string(3) "114"
}
[17]=>
array(1) {
["words"]=>
string(5) "-1.50"
}
[18]=>
array(1) {
["words"]=>
string(7) "-0,25"
}
[19]=>
array(1) {
["words"]=>
string(3) "122"
}
[20]=>
array(1) {
["words"]=>
string(3) ""
}
[21]=>
array(1) {
["words"]=>
string(1) "C"
}
[22]=>
array(1) {
["words"]=>
string(1) "A"
}
[23]=>
array(1) {
["words"]=>
string(5) "-1.50"
}
[24]=>
array(1) {
["words"]=>
string(4) "+0.0"
}
[25]=>
array(1) {
["words"]=>
string(5) "-1.25"
}
[26]=>
array(1) {
["words"]=>
string(7) "-0,25"
}
[27]=>
array(1) {
["words"]=>
string(3) "158"
}
[28]=>
array(1) {
["words"]=>
string(5) "-1.00"
}
[29]=>
array(1) {
["words"]=>
string(5) "-0.25"
}
[30]=>
array(1) {
["words"]=>
string(3) "100"
}
[31]=>
array(1) {
["words"]=>
string(1) "*"
}
[32]=>
array(1) {
["words"]=>
string(5) "-1.25"
}
[33]=>
array(1) {
["words"]=>
string(4) "+0.0"
}
[34]=>
array(1) {
["words"]=>
string(5) "U0=12"
}
[35]=>
array(1) {
["words"]=>
string(5) "PD=58"
}
}
["words_result_num"]=>
int(36)
["log_id"]=>
int(1455742838110100386)
}
系统需求是从上述数据中提取冒号后的两个数字。若采用常规遍历,需在遇到分隔符时设置标记以便后续提取,过程较为繁琐。能否在检测到特定字符串后直接读取后续元素?受Python或Java中迭代器概念的启发,查阅PHP文档后发现其同样支持迭代器功能。
参考PHP文档示例后迅速完成开发,耗时约五分钟。以下提供带注释的代码供参考:
$usefulNumList = [];
$wordsResult = new \ArrayIterator($wordsResult);//初始化数组迭代器,传入数组变量
foreach($wordsResult as $item){
$tempWords = $item['words'];
if(strpos($tempWords, '*') !== false){
if($tempWords === '*'){//有时候,*号会单独识别成一个字符串,有时候会和后面的数字识别到一起,如果是单独识别出来的,要把指针向后挪一位
$wordsResult->next();//实现方法是: 数组变更名->next()方法
}
//注意,调用了next()方法后,不能再用$item去取数组元素值,要用current()方法才能取到"下一个值"
array_push($usefulNumList, $this->getCleanNum($wordsResult->current()['words']));
$wordsResult->next();
array_push($usefulNumList, $this->getCleanNum($wordsResult->current()['words']));
}
}
代码中已对关键注意事项添加注释,封装逻辑清晰,便于理解与调用。
总结
以上就是关于PHP数组迭代器使用方法的详细介绍,更多相关内容请搜索本站历史文章或浏览下方推荐内容,感谢大家的支持!