2017-02-09 4 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

参照で一致するキー名でキー名を更新する方法がわかりません。そして

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

ループ:

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

Iアレイにデコードう:

$arr = json_decode($json, true); 

そして値としてキーとcaptionとしてfield付きフラットアレイにcolumnDefsを抽出results配列を作成し、マップキーを使用して新しい配列を作成し、新しいキーのマップ値を参照します。

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

関連する問題