php - 使用 PHP 获取 JSON 密钥
问题描述
我有一个看起来像这样的 JSON
$array = '{
"de": {
"name": "last_name",
"label": "Last Name",
"f_type": "input"
},
"en": {
"name": "last_name",
"label": "Last Name",
"f_type": "input"
}
}';
我想要实现的是当语言是英语时显示en
数组中的值
然后我像这样循环遍历 JSON。
$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>';
}
}
}
}
但是,如果我尝试获取语言键名并比较它是否是这样的特定值,则它不起作用
foreach ($json_values as $key) {
if( $key == 'en'){
echo "language is English";
}
}
所以,我不知道如何检查语言是什么并只显示该语言的值。
解决方案
$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>';
推荐阅读
- java - Jenkins artifactoryPublish 失败,HTTP 响应代码:405。HTTP 响应消息:不允许方法
- load-balancing - 对于本地集群,推荐的负载均衡解决方案是什么?
- dpdk - 运行 DPDK 示例程序时出现 EAL 初始化错误
- reactjs - 如何解决我的反应项目中的 npmstart 命令错误?
- c - 通过 fgets 从文件中获取内容时 C 中的分段错误适用于 Ubuntu,但不适用于 centos
- django - 尝试访问管理字体文件时,Django 在 AWS S3 中托管静态文件导致 CORS 错误
- javascript - iPhone设备中未显示图标-expo反应本机应用程序
- python - 在 Python 3.9.4 命令行上运行代码时出现“无效语法”错误
- javascript - 如何在组件中获取父数组长度?AngularJS
- php - 使用 PHP 下载远程文件时遇到问题(空 ZIP)