PHP更新JSON密钥名

PHP更新JSON密钥名,php,json,for-loop,Php,Json,For Loop,我有一个JSON输出,其中包含需要根据映射引用转换为字符串的数字键 // 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 => Na

我有一个JSON输出,其中包含需要根据映射引用转换为字符串的数字键

// 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

        }

    }
源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转换为字符串(
\u3>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

        }

    }

我会解码成一个数组:

$arr = json_decode($json, true);
然后将
columnDefs
提取到一个平面数组中,其中
字段
作为键,
标题
作为值:

$map = array_column($arr['columnDefs']['z'], 'caption', 'field');
然后循环
结果
数组,并使用映射键构建新数组,以引用新键的映射值:

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

我试图实现这一点,但有一些麻烦。我的地图和源数据来自同一个
json
。这里有
results(source)
columnDefs(map)
。您需要显示一个包含这两个内容的JSON示例。更新了OP,其中包含了我的结果和map