php将数组转换为简单值

时间:2017-12-15 01:29:13

标签: php arrays json

我在php中有这个json输出数组:

{
    "success": true,
    "attributes": {
        "token": "3RfvqeIhdTpwRpYOnPOKXmJe0avkmyS7m2NNQF6T",
        "type": "access",
        "client_id": "gozfly-support-wvjausbh",
        "user_id": "2",
        "expires": 1513301754,
        "scopes": {
            "accounts.profile.basic": {},
            "accounts.profile.emailaddress": {}
        }
    }
}

我需要将范围键转换为简单值,例如:

{
    "success": true,
    "attributes": {
        "token": "3RfvqeIhdTpwRpYOnPOKXmJe0avkmyS7m2NNQF6T",
        "type": "access",
        "client_id": "gozfly-support-wvjausbh",
        "user_id": "2",
        "expires": 1513301754,
        "scopes": {
            "accounts.profile.basic",
            "accounts.profile.emailaddress"
        }
    }
}

感谢任何帮助

1 个答案:

答案 0 :(得分:4)

<强> EDITED 正如上面的@ jh1711评论,预期输出不是有效的JSON字符串,它似乎是一个错字,我假设预期的输出是:

预期输出:

{
    "success": true,
    "attributes": {
        "token": "3RfvqeIhdTpwRpYOnPOKXmJe0avkmyS7m2NNQF6T",
        "type": "access",
        "client_id": "gozfly-support-wvjausbh",
        "user_id": "2",
        "expires": 1513301754,
        "scopes": [
            "accounts.profile.basic",
            "accounts.profile.emailaddress"
        ]
    }
}

<强>解决方案:

$data = <<<EOL
{
    "success": true,
    "attributes": {
        "token": "3RfvqeIhdTpwRpYOnPOKXmJe0avkmyS7m2NNQF6T",
        "type": "access",
        "client_id": "gozfly-support-wvjausbh",
        "user_id": "2",
        "expires": 1513301754,
        "scopes": {
            "accounts.profile.basic": {},
            "accounts.profile.emailaddress": {}
        }
    }
}
EOL;

$json = json_decode($data,true);
$json['attributes']['scopes'] = array_keys($json['attributes']['scopes']);

echo json_encode($json);