【发布时间】:2017-02-09 18:30:36
【问题描述】:
我有一个 JSON 输出,其中包含我需要根据映射引用将其转换为字符串的数字键。
源 JSON:
{
"results": {
"d": [
{
"_3": "Q0001",
"_85": "1"
},
{
"_3": "Q1009",
"_85": "1"
}
]
},
"columnDefs": {
"z": [
{
"field": "_3",
"caption": "QID",
"sortable": "true",
"resizeable": "true"
},
{
"field": "_85",
"caption": "Is Exempt",
"sortable": "true",
"resizeable": "true"
}
]
}
}
期望的结果:
[
{
"QID": "Q123",
"Emp ID": "E12345"
},
{
"QID": "X123",
"Emp ID": "E34567"
}
]
我正在解码 JSON 数组,以便循环遍历它。在这个数组中,有一个columnDefs 是我的地图。我将其存储为$reference = [];,以便将 ID 转换为字符串 (_3 > QID)
我一直在试图弄清楚如何用它在参考中匹配的键名来更新键名。
// Given a JSON string, convert the key names to the field names
function mapFields($json){
// Vars
$reference = [];
$arr = json_decode($json);
// Loop over our column defs and store the ID => Name
foreach($arr->x->columnDefs->z as $j){
$reference[$j->field] = $j->caption;
}
// Loop over the JSON and update the keys from ID to Name based on the reference
foreach($arr->x->results->d as $key => $value){
// Loop over all the keys
foreach($key as $k){
// Update the key name to its reference in the $reference array
}
}
【问题讨论】: