-1

I have a JSON that looks like this

$array = '{
    "de": {
        "name": "last_name",
        "label": "Last Name",
        "f_type": "input"
    },
    "en": {
        "name": "last_name",
        "label": "Last Name",
        "f_type": "input"
    }
}';

and what I want to achieve is when the language is English to show values from the en array

Then I am looping through the JSON like this.

$json_values = json_decode( $array, true);

foreach ($json_values as $key) {
    foreach ($key as $item => $value) {
        if ($item == 'label') {
            $label = $value;
        }
        if ($item == 'name') {
            $name = $value;
        }
        if ($item == 'f_type') {
            if ($value == 'input') {
            echo  '<div class="form-group"><label for="usr">'.$label.':</label>
                    <input type="text" value="'.$name.'" class="form-control"></div>';
            }
        }
    }
}

However, if I try to get the language key name and compare if it is a specific value like this it is not working

foreach ($json_values as $key) {
   if( $key == 'en'){
      echo "language is English";
      }
}

So, I don't know how to check what the language is and to show values for that language only.

lStoilov
  • 1,256
  • 3
  • 14
  • 30
  • 1
    Surely `$json_values['en']` is the easiest way. – Nigel Ren Jul 06 '21 at 06:06
  • 1
    Forget about the fact that you received the data initially as JSON. You decoded it to a dictionary already, so its former representation is irrelevant. That said, are you looking for the `foreach ($sequence as $key => $value) ...` syntax? – Ulrich Eckhardt Jul 06 '21 at 06:06
  • 1
    Accessing the values via something like `$json_values[$language]['name']` is surely preferable to looping over them. If you want to loop over all languages, then it's `foreach ($json_values as $language => $data) { echo "... $data[name] ..."; }`. – deceze Jul 06 '21 at 06:08
  • @NigelRen, that will not work. as I need to know the name of the language key that I don't know if exists, as there might be other languages too. So, I will need to put the key name into a string and then compare it. – lStoilov Jul 06 '21 at 06:16
  • `foreach ($json_values as $key)` loops over the *values*, not the keys! Even if you name the variable "`$key`", it's still the values. – deceze Jul 06 '21 at 06:20

1 Answers1

2
$json = '{
    "de": {
        "name": "last_name",
        "label": "Last Name",
        "f_type": "input"
    },
    "en": {
        "name": "last_name",
        "label": "Last Name",
        "f_type": "input"
    }
}';

$json = json_decode($json,true);
$lang = 'en';

if($lang == 'en'){
    $values = $json[$lang];
} else {
    $values = $json['de'];
}

echo  '<div class="form-group"><label for="usr">'.$values['label'].':</label><input type="text" value="'.$values['name'].'" class="form-control"></div>';
marts
  • 104
  • 5