Home > front end >  PHP delete json element
PHP delete json element

Time:01-13

the json data is

[name] => stdClass Object
        (
            [first] => Andy
            [middle] => 
            [last] => James
        )

[age] => 18
[lovely] => Array
        (
            [0] => running
            [1] => coding
            [2] => -
        )

I need to delete [lovely][2] because that's no answer, but I write this code, it's not working...

$keysToRemove = array("N/A", "-", "");

// Recursively iterate through object and remove keys with specified values
function cleanObject($obj) {
    foreach ($obj as $key => $value) {
        if (is_object($value) || is_array($value)) {
            $obj->$key = cleanObject($value);
        } else {
            if (in_array($value, $GLOBALS['keysToRemove'])) {
                unset($obj->$key);
            }
        }

    }
    //print_r($obj);
    return $obj;
}

the output is

{"name":
    {"first":"Andy","last":"James"},"age":18,
    "lovely":["running","coding","-"]}

it's error.

the correct output is

{"name":{"first":"Andy","last":"James"},"age":18,
    "lovely":["running","coding"]}

how can delete "-"??

CodePudding user response:

As "lovely" key is an Array and not an Object, you can't use Array->Property expression like you do in case of Object. For this purpose, add following block to your code:

$string = '{"name": {"first": "Andy", "middle": "", "last": "James"}, "age": "18", "lovely": ["running", "coding", ""]}';

$json = json_decode($string);

$keysToRemove = array("N/A", "-", "");

function cleanObject ($obj) {
  foreach ($obj as $key => $value) {
    if (is_object($value) || is_array($value)) {
      $obj->$key = cleanObject($value);
    } else {
        if (in_array($value, $GLOBALS['keysToRemove'])) {
          if (is_array($obj)) {
            unset($obj[$key]);
          } else {
            unset($obj->$key);
          }
        }
      }
  }
  return $obj;
}

var_dump(cleanObject($json));
  • Related