如何在php中以小写形式转换json键

时间:2016-12-29 09:46:29

标签: php json

如何在php中以小写形式转换json键,

例如:

"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" : ""
                }
            }
        }

1 个答案:

答案 0 :(得分: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;