PHP更新JSON密钥名称

时间:2017-02-09 18:30:37

标签: php json for-loop

我有一个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

        }

    }

1 个答案:

答案 0 :(得分: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;
    }
}