Reputation: 4187
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
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.
Upvotes: 3
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
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
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