PHP代码问题:无符合条件作者时如何返回默认ID?
PHP代码优化:无符合条件作者时返回默认ID
现有一段PHP代码,可返回文章文本中出现次数超过一次的作者ID,运行正常。现需优化代码,使其在没有作者符合该条件时返回默认ID。以下是原始正常代码及添加else后失效的尝试代码:
原始正常代码
<?php $article = "This is a article is written by the three authors - Smith, Jackson, Peters. Peterson is not author. The main author of the article is Jackson."; $authors = [1=>'Smith', 2=>'Jackson', 3=>'Peters']; foreach ($authors as $id=>$author) { preg_match_all('/\b'.$author.'\b/', $article, $match); if (count($match[0])>1) { return $id; } } ?>
失效的尝试代码
<?php $article = "This is a article is written by the three authors - Smith, Jackson, Peters. Peterson is not author. The main author of the article is Jackson."; $authors = [1=>'Smith', 2=>'Phillips', 3=>'Peters']; foreach ($authors as $id=>$author) { preg_match_all('/\b'.$author.'\b/', $article, $match); if (count($match[0])>1) { return $id; } else { return '1899'; } } ?>
问题分析
尝试代码失效的核心原因是:循环第一次执行时,只要当前作者不满足出现次数>1的条件,就会触发else分支里的return语句,直接终止循环并返回默认ID,根本没机会检查后续的作者。
解决方案
正确的逻辑是先遍历完所有作者,确认没有符合条件的后再返回默认ID。可以先初始化一个默认值,遍历过程中找到符合条件的作者就更新这个值,遍历结束后返回最终结果:
<?php $article = "This is a article is written by the three authors - Smith, Jackson, Peters. Peterson is not author. The main author of the article is Jackson."; $authors = [1=>'Smith', 2=>'Phillips', 3=>'Peters']; $defaultId = '1899'; $resultId = $defaultId; foreach ($authors as $id=>$author) { preg_match_all('/\b'.$author.'\b/', $article, $match); if (count($match[0])>1) { $resultId = $id; // 如果只需要返回第一个符合条件的作者,这里可以直接break跳出循环 break; } } return $resultId; ?>
如果需要返回所有出现次数超过一次的作者ID,可以把结果改成数组形式:
<?php $article = "This is a article is written by the three authors - Smith, Jackson, Peters. Peterson is not author. The main author of the article is Jackson. Smith also contributed to this article."; $authors = [1=>'Smith', 2=>'Jackson', 3=>'Peters']; $defaultId = '1899'; $resultIds = []; foreach ($authors as $id=>$author) { preg_match_all('/\b'.$author.'\b/', $article, $match); if (count($match[0])>1) { $resultIds[] = $id; } } // 如果没有符合条件的作者,返回默认ID;否则返回所有符合条件的ID数组 return empty($resultIds) ? $defaultId : $resultIds; ?>
内容的提问来源于stack exchange,提问作者Boris Smolyanov
相关产品推荐
相关产品推荐

