Home » Php » How to display dynamic keys and values of json data in html using php

How to display dynamic keys and values of json data in html using php

Posted by: admin February 25, 2020 Leave a comment

Questions:

The below values are dynamic in JSON format, which will change for every entry.
1) {"ABCD":{"Hindi":"82"},"EFGH":{"English":"78"},"IJKL":{"Urdu":"82"},"MNOP":{"Sanskrit":"78"}}

I want to display in single cell in a column, as shown below. how can i achieve that using PHP

REMARKS

ABCD: Hindi = 82,

EFGH: English = 78,

IJKL: Urdu = 82,

MNOP: Sanskrit = 78

How to&Answers:

Use

$arr = json_decode($data, true); 

Then, iterate over data using 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 will be :

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

Answer:

I am going to assume that you have the the json as a string:

$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;

I didn’t use json_decode because I find the nested arrays easier to parse with loops.
I am aware that there are a few shortcuts you can take instead of doing what I did (but copying is easier).

Also, output would be:

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

Hope this helps!