Hai Truong IT
Hai Truong IT

Reputation: 4187

How to remove value from array json php?

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?

Upvotes: 1

Views: 7607

Answers (4)

hsuk
hsuk

Reputation: 6870

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

Upvotes: 3

cartina
cartina

Reputation: 1429

$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]);

Upvotes: 0

Dipali Vasani
Dipali Vasani

Reputation: 2536

$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);

Upvotes: 0

laurent
laurent

Reputation: 90863

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);

Upvotes: 1

Related Questions