Home > Software design >  PHP and JSON delete or replace specific Array
PHP and JSON delete or replace specific Array

Time:05-11

Hey Guys so i have this current problem:

Im building a website which is using a feed based on a json file. No i want to create a dashboard where users can delete or submit there data so its being built in the feed. The data append for the feed already works but i just don't know how i could delete a specific array so users can delete their entrys.

Json code to understand my problem

[
{
"name":"name_entry",
"email":"email_entry",
"data":"data_entry"
},
{
"name":"name_entry",
"email":"email_entry",
"data":"data_entry"
},
{
"name":"name_entry",
"email":"email_entry",
"data":"data_entry"
}
]

Lets no say that the user decides to delete his entry, for this example the second array or [1] how can i delete the complete array without losing the other ones with PHP?

Already thanks for your time :)

CodePudding user response:

  1. Remove specific array :

    unset($array[1]);
    
  2. Remove specific array and rearrange the array index :

    1. unset($array[0]); // remove item at index 0
    2. $array_2 = array_values($array); // 'reindex' array

CodePudding user response:

One way to do is this:

Step 1- Traverse the array.

Step 2- Find the element you're looking for

Step 3- Unset it

Sample code:

$index=0;
foreach($json_data as $element) {
   //check the property of every element
   if(is the current element to be deleted?){
      unset($json_data[$index]);
   }
   $index  ;
}
  • Related