2016-12-29 42 views
-4

如何JSON密鑰轉換在PHP小寫,如何轉換JSON關鍵小寫在PHP

例如:

"Object" : { 
      "objectType" : "Activity", 
      "id" : "http://activitystrea.ms/schema/1.0/page", 
      "Definition" : { 
       "name" : { 
        "en-US" : "What Is Information Security?" 
       }, 
       "Description" : { 
        "en-US" : "" 
       } 
      } 
     } 

以上數據應該是這樣的:

"object" : { 
      "objecttype" : "Activity", 
      "id" : "http://activitystrea.ms/schema/1.0/page", 
      "definition" : { 
       "name" : { 
        "en-us" : "What Is Information Security?" 
       }, 
       "description" : { 
        "en-us" : "" 
       } 
      } 
     } 
+0

嗯,也許只是使用小寫名稱來生成該JSON? –

+0

這會幫助你http://php.net/manual/en/function.array-change-key-case.php –

回答

0

你的json代碼無效。你必須在http://php.net/manual/de/function.array-change-key-case.php

與把它包起來「{」和「}」

檢查array_change_key_case()功能這裏是你正在尋找的解決方案。

// Your input json wrapped with "{" and "}" 
$json = '{ "Object" : { "objectType" : "Activity", "id" : "http://activitystrea.ms/schema/1.0/page", "Definition" : { "name" : { "en-US" : "What Is Information Security?" }, "Description" : { "en-US" : "" } } } }'; 

// json_decode() converts json to array 
$array = json_decode($json, true); 

// key case changer. changes key recursively 
// Source php.net 
function array_change_key_case_recursive($arr) 
{ 
    return array_map(function($item){ 
     if(is_array($item)) 
      $item = array_change_key_case_recursive($item); 
     return $item; 
    },array_change_key_case($arr)); 
} 


$new_array = array_change_key_case_recursive($array); 

// You expected json output 
$new_json = json_encode($new_array); 

echo $new_json;