【问题标题】:How to display dynamic keys and values of json data in html using php如何使用php在html中显示json数据的动态键和值
【发布时间】:2020-02-18 16:56:18
【问题描述】:

以下值是 JSON 格式的动态值,每个条目都会更改。 1){"ABCD":{"Hindi":"82"},"EFGH":{"English":"78"},"IJKL":{"Urdu":"82"},"MNOP":{"Sanskrit":"78"}}

我想在一列的单个单元格中显示,如下图。如何使用 PHP 实现这一目标

备注

ABCD:印地语 = 82,

EFGH:英语 = 78,

IJKL:乌尔都语 = 82,

MNOP:梵文 = 78

【问题讨论】:

  • 解码然后foreach

标签: php json


【解决方案1】:

使用

$arr = json_decode($data, true); 

然后,使用 foreach 遍历数据

$final = [];
$arr = json_decode($a, true); 

foreach($arr as $key => $val){

    $out = '';
      foreach($val as $k => $v){

        $out .= $k."=" .$v;

      }
     $f = $key . ":" . $out . "<br>";

    $final[] = $f; 

   }

O/P 将是:

Array ( [0] => ABCD:Hindi=82
[1] => EFGH:English=78
[2] => IJKL:Urdu=82
[3] => MNOP:Sanskrit=78
)

【讨论】:

    【解决方案2】:

    我将假设您将 json 作为字符串:

    $str = '{"ABCD":{"Hindi":"82"},"EFGH":{"English":"78"},"IJKL":{"Urdu":"82"},"MNOP":{"Sanskrit":"78"}}';
    
    $str = str_replace("{", "array(", $str);
    $str = str_replace("}", ")", $str);
    $str = str_replace(":", ",", $str);
    $obj = "";
    $newstr = "";
    
    for ($i = 0; $i < count($obj); $i++) {
      $e = $obj[$i];
      $zero = 0;
      $one = 1;
      $last = intval(count($obj)) - $one;
      if (gettype($obj[$i]) == gettype(array(0,0))) {
        //optional if to prevent the comma at the end.
        if ($i != $last) {
          $newstr = $newstr."$e[$zero] = $e[$one], <br/>\n"; //<br/> if displayed as html
        } else {
          $newstr = $newstr."$e[$zero] = $e[$one]";
        }
      } else {
        $newstr = $newstr."$e : ";
      }
    }
    
    echo $newstr;
    

    我没有使用json_decode,因为我发现嵌套数组更容易用循环解析。
    我知道你可以采取一些捷径来代替我做的事情(但复制更容易)。

    另外,输出将是:

    ABCD: Hindi = 82,
    EFGH: English = 78,
    IJKL: Urdu = 82,
    MNOP: Sanskrit = 78
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2019-01-14
      • 2014-02-25
      • 2016-01-11
      • 2012-08-25
      • 2021-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多