Get JSON key with PHP

47 views Asked by At

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.

1

There are 1 answers

0
marts On BEST ANSWER
$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>';