简体   繁体   中英

php convert array to simple values

I have this json output array in php:

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

I need to convert the scopes keys to simple values, like:

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

Any help is appreciated

EDITED As @jh1711 comment above, the expected output is not a valid JSON string, it seems like a typo, I assume that expected output is:

Expected Output:

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

Solution:

$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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM