Home > Enterprise >  Remove key-value from Json object without loop in PHP
Remove key-value from Json object without loop in PHP

Time:02-21

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?

CodePudding user response:

unset($array['FIRST']['roles']);
unset($array['SECOND']['roles']);
  • Related