Reputation: 967
I am trying to open a .json file and check if the file contains an array identified by its key. If so, I want to delete it and write the file back to the server. However, I am not having any luck and I think it is my misunderstanding of arrays of arrays in PHP:
PHP:
$song_id = "j8sUV-ykOB";
$file = "file.json";
$song_list = json_decode(file_get_contents($file),true);
foreach($song_list as $song){
if(in_array($song_id,$song_list)){
unset($song);
file_put_contents($file,json_encode($song_list,JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT));
}
}
file.json:
{
"uKrb3eNCf": [
"Thunder Rolls",
"c"
],
"kdOzCKjKN-": [
"Turn the Page",
"a"
],
"bDreHgZgxF": [
"Wild Nights",
"a"
],
"oeNcwqZJS": [
"Every day is a winding road",
"b,j"
],
"j8sUV-ykOB": [
"Testin",
"b"
]
}
Upvotes: 0
Views: 2943
Reputation: 174
<?php
$song_id = "j8sUV-ykOB";
$file = "file.json";
$song_list = json_decode(file_get_contents($file),true);
$new_array = array();
foreach($song_list as $key => $song){
if($key != $song_id){
$new_array[$key] = $song;
}
}
file_put_contents($file,json_encode($new_array,JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT));
?>
This code is successfully work foe me. In foreach check $song_id is equal to Key of array or not. if not insert this array in new array. So after complete all loop of foreach, new array created. So write json file again after decoded this new array. Thanks
Upvotes: 0
Reputation: 1484
In your case you can avoid a for loop because of the way your data is structured, we can directly call to the specific array of data in your $song_list
array.
Your song ID are keys so you can go directly and check if the key exists in your song_list array, if it does exist then unset that key.
Here is it in action:
<?php
$song_id = "j8sUV-ykOB";
$file = "file.json";
$song_list = json_decode(file_get_contents($file),true);
if (array_key_exists($song_id, $song_list))
{
unset($song_list[$song_id]);
file_put_contents($file,json_encode($song_list,JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT));
}
Upvotes: 2
Reputation: 62676
What you want is to unset
the $song_list[$key]
, not the $song
variable:
foreach($song_list as $key => $song){
if(in_array($song_id,$song_list)){
unset($song_list[$key]);
}
}
file_put_contents($file,json_encode($song_list,JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT));
The $song
variable in your code contains the value of the current element in your json file, doing unset
on that value makes no sense.
Upvotes: 1