【问题标题】:PHP Update JSON Key NamesPHP 更新 JSON 键名
【发布时间】: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

        }

    }

【问题讨论】:

    标签: php json for-loop


    【解决方案1】:

    我会解码成一个数组:

    $arr = json_decode($json, true);
    

    然后将columnDefs 提取到以field 为键、caption 为值的平面数组:

    $map = array_column($arr['columnDefs']['z'], 'caption', 'field');
    

    然后循环results数组并使用映射键构建新数组以引用新键的映射值:

    foreach($arr['results']['d'] as $key => $val) {
        foreach($val as $k => $v) {
            $result[$key][$map[$k]] = $v;
        }
    }
    

    【讨论】:

    • 我正在尝试实现这一点,但遇到了一些麻烦。我的地图和源数据来自同一个json。有results (source)columnDefs (the map)
    • 您需要展示一个包含两者的 JSON 示例。
    • 用包含我的结果和地图的 json 更新了 OP
    猜你喜欢
    • 2021-06-16
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 2021-12-31
    • 2019-02-05
    • 1970-01-01
    相关资源
    最近更新 更多