在 PHP 中匹配数组内的相似性

Match Similarity inside array in PHP

提问人:rana wseef 提问时间:3/4/2021 最后编辑:rana wseef 更新时间:3/4/2021 访问量:37

问:

我有一个这样的json文件:

{
  "results": [
    {
      "category_id": 13732,
      "name": "Artificial Fruits & Vegetables",
      "category_tree": "Home, Garden & Pets > Home Furnishings & Decor > Artificial Plants & Flowers",
      "google_category": {
        "id": 6265,
        "tree": "Home & Garden > Decor > Artificial Flora",
        "name": "Artificial Flora",
        "level": 3
      }
    },
    {
      "category_id": 13981,
      "name": "Vegetables",
      "category_tree": "Home, Garden & Pets > Garden & Outdoor Living > Plants, Seeds & Bulbs > Outdoor Plants",
      "google_category": {
        "id": 6762,
        "tree": "Home & Garden > Plants > Indoor & Outdoor Plants",
        "name": "Indoor & Outdoor Plants",
        "level": 3
      }
    },
    {
      "category_id": 17779,
      "name": "Vegetables",
      "category_tree": "Food & Drink > Food Cupboard > Tins, Cans & Jars",
      "google_category": {
        "id": 5798,
        "tree": "Food, Beverages & Tobacco > Food Items > Fruit & Vegetables > Canned & Jarred Vegetables",
        "name": "Canned & Jarred Vegetables",
        "level": 4
      }
    },
    {
      "category_id": 17800,
      "name": "Vegetables",
      "category_tree": "Food & Drink > Frozen Food",
      "google_category": {
        "id": 5793,
        "tree": "Food, Beverages & Tobacco > Food Items > Fruit & Vegetables > Fresh & Frozen Vegetables",
        "name": "Fresh & Frozen Vegetables",
        "level": 4
      }
    },
    {
      "category_id": 17806,
      "name": "Vegetables",
      "category_tree": "Food & Drink > Fruit & Veg",
      "google_category": {
        "id": 430,
        "tree": "Food, Beverages & Tobacco > Food Items > Fruit & Vegetables",
        "name": "Fruit & Vegetables",
        "level": 3
      }
    }
  ]
  }

我想获得与此字符串最相关/最相似的类别

“Ocado 自有品牌/水果、蔬菜和沙拉/蔬菜”

通过 JSON 中每个类别对象的类别树或名称进行匹配。

请帮忙,我是PHP新手

...更新。。。

<?php
similar_text("Beverages & Tobacco > Food Items > Fruit & Vegetables > Fresh & Frozen Vegetables","Ocado Own-Label/Fruit, Vegetables & Salad/Vegetables",$percent);
echo $percent;
?>

我想使用similar_text函数进行搜索并返回最匹配的 json 对象/类别

PHP JSON 匹配

评论

2赞 jibsteroos 3/4/2021
向我们展示您尝试过的东西,您最好的尝试(代码)。什么不能按预期工作?你遇到任何错误吗?建议阅读 如何问.
0赞 rana wseef 3/4/2021
问题已更新
0赞 CBroe 3/4/2021
因此,在一个循环中执行此操作,如果当前项目的百分比高于您之前的最高百分比,则当前项目将成为您的新“最佳候选者”。
0赞 rana wseef 3/4/2021
第一场比赛呢?如果没有,我将如何与之前的比赛进行比较
0赞 ADyson 3/4/2021
为此,您只需要在逻辑中加入一个特殊情况,用于当前一个匹配项为 null 时 - 在这种情况下,当前项目始终成为“顶部”项目(显然)。

答:

0赞 rana wseef 3/4/2021 #1
$decode = json_decode($json);
for($i=0; $i<count($decode->results); $i++){
    
    similar_text($decode->results[$i]->google_category->tree,"Ocado Own-Label/Fruit, Vegetables & Salad/Vegetables",$percent);
    $myarr[$i]=$percent;
}

$maxmatchcategory = array_search(max($myarr), $myarr);
echo $decode->results[$maxmatchcategory]->category_id.'<br>';