John Davidson

Remove key-value from Json object without loop in PHP

0 comments
Message:


I have a JSON of the following format-


{
"FIRST": {
"group": {
"group_name": "first grp name",
"group_code": "FIRST"
},
"roles": [
{
"role_name": "Basic User",
"role_code": "FIRST_USER",
"role_description": "Basic user access",
"group_code": "FIRST"
}
]
},
"SECOND": {
"group": {
"group_name": "second grp name",
"group_code": "SECOND"
},
"roles": [
{
"role_name": "BASIC USER",
"role_code": "SECOND_USER",
"role_description": "SECOND User",
"group_code": "SECOND"
}
]
}
}

I need to remove the "roles" key and its value from both "FIRST" and "SECOND".
For this I do-


foreach($obj as $key => $val) {
unset($val['roles']);
$obj[$key] = $val;
}

And this gives me back the object just without the "roles". Is there a better way to do this without the loop?



My Answer:
{
"name": "John",
"age": 30,
"city": "New York"
}_

I want to remove the "age" key from this JSON object without using a loop in PHP. Here's how you can achieve this:

php
$json = '{
"name": "John",
"age": 30,
"city": "New York"
}';

$data = json_decode($json, true);

unset($data['age']);

$newJson = json_encode($data);

echo $newJson;


This code will output the following JSON object:

json
{
"name": "John",
"city": "New York"
}

Rate this post

3 of 5 based on 8811 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us