【问题标题】:Get Value from nested JSON File in PHP with Placeholder使用占位符从 PHP 中的嵌套 JSON 文件获取值
【发布时间】:2022-11-23 04:42:57
【问题描述】:

我想写我自己的小翻译功能。

我的 JSON 文件如下所示:

{
"start": {
  "body": {
    "headline": "Hello, world!"
   }
  }
}

在我的 PHP 前端中,我只想为翻译后的字符串编写占位符。所以我做

<h1><?php trans('start.body.headline'); ?></h1>

我的 PHP 函数很简单,看起来像:

function trans($string) {

    if (!isset($_GET['langID']))
        $lang = 'de';
    else
        $lang = $_GET['langID'];

    $str = file_get_contents('lang/'. $lang . '.json');
    $json = json_decode($str);
    $string = str_replace('.', '->', $string);
 
    echo $json->$string;

  }

但我没有得到结果。

我的函数中的 $string 是正确的:

start->body->headline

当我写的时候:

echo $json->start->body->headline;

我得到“你好,世界”。

echo $json->$string; 

相同但不起作用。为什么?

【问题讨论】:

    标签: php json object nested placeholder


    【解决方案1】:

    因为您使用的是相同的变量名$字符串对于函数参数,在这里使用其他变量名。

    $keyword = str_replace('.', '->', $string);
    
    echo $json->{$keyword};
    

    你也可以使用返回方法

    function trans($string) {
    
    if (!isset($_GET['langID']))
        $lang = 'de';
    else
        $lang = $_GET['langID'];
    
    $str = file_get_contents('lang/'. $lang . '.json');
    $json = json_decode($str);
    $keyword = str_replace('.', '->', $string);
    
    return $json->{$keyword};
    }
    

    而不是使用短的方式回声在 html 中

    <h1><?= trans('start.body.headline'); ?></h1>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-19
      • 2014-05-09
      • 1970-01-01
      • 2016-08-22
      • 2021-10-25
      • 1970-01-01
      • 2017-01-19
      • 1970-01-01
      相关资源
      最近更新 更多