You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何查找与搜索文本同唯一编码uniqueid的其他关联文本

实现方案

方案1:预处理数组结构(推荐,性能更高)

提前把数据按uniqueid分组,同时建立文本到uniqueid的映射,搜索时不需要二次遍历全量数组,适合数据量较大的场景。

// 重构数据生成逻辑,替换原有$output生成代码
$dictData = [];
$textToUniqueId = [];

foreach($results as $row) {
    $uniqueid = $row['uniqueid'];
    $language = $row['language'];
    $text = trim($row['description']);
    // 按uniqueid分组存储多语言文本
    $dictData[$uniqueid][$language] = $text;
    // 建立文本到uniqueid的映射,统一转小写避免大小写匹配问题
    $mappingKey = mb_strtolower($text);
    // 如果存在同文本对应多组uniqueid的情况,这里可以改成数组存储
    $textToUniqueId[$mappingKey] = $uniqueid;
}

搜索逻辑代码示例:

// 假设搜索词来自前端提交的参数
$searchKeyword = trim($_POST['search_text']);
$searchKey = mb_strtolower($searchKeyword);
$searchResult = [];

if (isset($textToUniqueId[$searchKey])) {
    $targetUniqueId = $textToUniqueId[$searchKey];
    // 直接取同uniqueid下的所有关联文本
    $searchResult = $dictData[$targetUniqueId];
}

// 输出$searchResult即可得到所有关联文本

方案2:直接遍历原有数组(适合小数据量场景)

如果不想修改原有$output数组的生成逻辑,可以直接遍历两次数组实现功能:

$searchKeyword = trim($_POST['search_text']);
$searchKey = mb_strtolower($searchKeyword);
$matchedUniqueId = '';
$relatedTexts = [];

// 第一步:查找匹配文本对应的uniqueid
foreach ($output as $item) {
    if (mb_strtolower($item['text']) === $searchKey) {
        $matchedUniqueId = $item['uniqueid'];
        break;
    }
}

// 第二步:查找同uniqueid下的所有关联条目
if (!empty($matchedUniqueId)) {
    foreach ($output as $item) {
        if ($item['uniqueid'] === $matchedUniqueId) {
            $relatedTexts[] = $item;
        }
    }
}

// $relatedTexts即为需要的结果

扩展说明

  • 如果需要实现模糊匹配而非精确匹配,将精确相等的判断替换为mb_stripos($item['text'], $searchKeyword) !== false即可实现不区分大小写的包含匹配
  • 如果存在相同文本对应多组uniqueid的场景,将$textToUniqueId改为存储数组,收集所有匹配的uniqueid后遍历取关联内容即可

内容的提问来源于stack exchange,提问作者afaaro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 03:45:06