1

I have a sample code:

$json_encode = '{"OS":"Android","Title":"Galaxy"}';
$json_decode = json_decode($json_encode);
foreach($json_decode as $key => $value) {
   if($key == 'Title') {
       unset($key); 
   }
}
print_r(json_encode($json_decode));

But result can't remove key='Title' from that json string, how to fix it?

4 Answers 4

3

You don't need those extra lines of code, if the Title index comes always, then you can unset the Title index directly :

$json_encode = '{"OS":"Android","Title":"Galaxy"}';
$json_decode = json_decode($json_encode);
unset($json_decode['Title']); 

See the link below for more information on PHP Array Unset function, you are making mistake on simple syntax.

PHP Array Unset

Sign up to request clarification or add additional context in comments.

Comments

1

You forgot to include the array in the unset statement. It should be:

unset($json_decode[$key]); 

Actually, for your particular example, you don't even need a loop, you can unset the value directly.

Also to get an associative array from the json_encode function, you need to add another parameter:

$json_decode = json_decode($json_encode, true);

Comments

0
$json_encode = '{"OS":"Android","Title":"Galaxy"}';
$json_decode = json_decode($json_encode, true);
foreach ($json_decode as $key => $value) {
    if (in_array('Title', $value)) {
        unset($json_decode[$key]);
    }
}
$json_encode = json_encode($json_decode);

Comments

0
$json_decode = json_decode($json_encode,TRUE);

If "TRUE" is not passed, json_decode returns an object.

Also replace unset($key) with unset($json_decode[$key]);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.