How can I traverse a multi level php object and unset the deepest node dynamically

114 views Asked by At

I have an object that is in the form:

CommentID: [
  "UserID": UserID, 
  "Status": "active/deleted", 
  "DateTime": "DateTime", 
  "Comment": "CommentText",  
  "Likes": [
    UserID: DateTime of Like, 
    UserID: DateTime of Like...
  ], 
  "Comments": [same as parent]
]

This means, I could have multiple levels of comments -> A comment on a comment on a comment.

If I want to delete a comment, I get from the view the full chain of CommentIDs... parent commentID, sub-parent, sub-sub.. etc..

How can I now unset this particular comment.

Something like this:

Imagine I get the following: 1;2;3 where 1 is CommentID of parent, 2 is CommentID of child of parent and 3 is CommentID of child of child.

This comes to me as a variable in PHP.

I would like now to unset 3..

ideally, I'd write,

unset($object->{1}->{2}->{3}); and it will work.

But, i can't assume the number of levels. So I have to somehow loop through the comment ID's and figure out a way.

1

There are 1 answers

7
Seth McClaine On BEST ANSWER

Without an example of what you actually have, I'm assuming you have an array of comments, and inside of each comment could be an array of more comments inside the comments field.

If this is the case you would be doing something along the lines of

unset($object->comments[1]->comments[2]->comments[3]);

This would unset the third comment, of the second comment of the first comment in your object.

If this is not the answer you are looking for, please give an actually example.

Sudo Recursion example

function unsetLowestComment($comment) {
  $commentsLength = count($comment->comments);
  if($commentsLength > 0) {
    unsetLowestComment($comment->comments[$commentsLength -1]);
  } else {
    unset($comment);
  }
}

unsetLowestComment($commentInQuestion);