2016-12-29 37 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;