I have a json array. in which i have 3 values. when i delete first or second value the resultant array after deletion is one format. But when i delete the last value always the resultant array changes. i am echoing the array by converting it back to string.
When i delete any value except the last one, that is like 1st or 2nd or any other value
result = {"1":{"name":"cat"},"2":{"name":"elephant"}}
Here i deleted first value - dog
$animals = '{
"0":{"name":"dog"},
"1":{"name":"cat"},
"2":{"name":"elephant"}
}';
$animals = json_decode($animals, true);
$del_value = "elephant";
$loginArray = array('name' => $del_value);
if (in_array($loginArray, $animals)) {
foreach ($animals as $key => $value) {
if (in_array($del_value, $value)) {
unset($animals[$key]);
}
}
}
$animals_string = json_encode($animals);
echo $animals_string;
but When i delete the last value it creates different format
result = [{"name":"dog"},{"name":"cat"}]
Here i deleted last value - elephant
$animals = '{
"0":{"name":"dog"},
"1":{"name":"cat"},
"2":{"name":"elephant"}
}';
$animals = json_decode($animals, true);
$del_value = "elephant";
$loginArray = array('name' => $del_value);
if (in_array($loginArray, $animals)) {
foreach ($animals as $key => $value) {
if (in_array($del_value, $value)) {
unset($animals[$key]);
}
}
}
$animals_string = json_encode($animals);
echo $animals_string;