简体   繁体   中英

PHP Update JSON Key Names

I have a JSON output that contains numeric keys that I need to convert to strings based on a mapping reference.

Source 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"
            }
        ]
    }
}

Desired Result:

[
{
    "QID": "Q123",
    "Emp ID": "E12345"
},
{
    "QID": "X123",
    "Emp ID": "E34567"
}
]

I am decoding the JSON array so that I can loop over it. Within this array, there is a columnDefs that is my map. I am storing this as a $reference = []; so that I have the conversion of ID to String ( _3 > QID )

I am stuck trying to figure out how to update the key names with that of the one it matches in the reference.

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

        }

    }

I would decode into an array:

$arr = json_decode($json, true);

Then extract the columnDefs to a flat array with field as the keys and caption as the values:

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

Then loop the results array and build the new array using the map keys to reference the map value for the new key:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM