2017-02-09 64 views
0

我有一個JSON輸出包含數字鍵,我需要根據映射參考轉換爲字符串。PHP更新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爲String(_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

我將解碼成一個數組:

$arr = json_decode($json, true); 

然後用field作爲鍵和caption作爲值提取columnDefs到平坦陣列:

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

然後循環的results array並使用map鍵構建新數組以引用新鍵的映射值:

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

我想實現這個,但有一些麻煩。我的地圖和源數據來自同一個'json'。有'results(source)'和'columnDefs(map)'。 – SBB

+0

您將需要顯示兩個JSON的示例。 – AbraCadaver

+0

使用包含我的結果和地圖的json更新OP – SBB