匹配并替换两个 JSON 文件的内容

时间:2021-01-03 21:28:23

标签: php json

我尝试将两个 JSON 文件与那里的代码进行匹配。 所以第一个包含产品信息的文件只有代码(如 GRM),但对于我的网站,我需要在代码后面显示代码名称 (GRAMM)(存储在 codelist.json 中)。

第一个 JSON 文件:product.json

  • 代码为“GRM”
          "measurement": {
            "grossWeight": 431,
            "grossWeightUom": "GRM",
            "netContent": "400",
            "netContentUom": "MLT",
            "isBasePriceDeclarationRelevant": "TRUE",
            "priceComparison": 400,
            "priceComparisonUom": "MLT",
          }

第二个 JSON 文件:codelist.json

  • 代码为“GRM”,代码名称为“Gramm”
        {
            "ID": "M072",
            "Attribut": "Nährwertkennzeichnung: Bezugsgröße Maßeinheit",
            "PROMIS Codelist Name": "PROMIS_NUTRITIONAL_VALUE_REFERENCE_LEVEL",
            "Code": "GRM",
            "Language": "de",
            "Code Name": "Gramm",
        },

已经尝试过php代码:

                    $filename = 'codes/codelist.json';
                    $codefile = file_get_contents($filename);
                    $codejson = json_decode($codefile);

                    foreach($codejson as $Code) {
                        if($Code->Code == 'GRM') {
                            echo "Code Name";
                        }
                    }

或者对“StrgReplace”有什么想法?

希望有人能帮助我。

谢谢!

1 个答案:

答案 0 :(得分:0)

//Create new array sorted by code for easier later use
foreach($codelist as $key => $value)
{
   $codelistByCode[$value['Code']] = $value;
}

// Print out correct codename (you could make this as a function)
if($product['measurement']['grossWeightUom'] === 'GRM')
{
   echo $codelistByCode['GRM']['Code Name'];
}
相关问题