Delete an element from a JSON object - PHP

0

I have a JSON file like this one:

[
 {
  "NAME": "Algo",
  "ALIAS": "Algo"
 },
 {
  "NAME": "Otro",
  "ALIAS": "Otra cosa"
 }
]

I need to delete the second element with the index number already (there are many more elements (urls)). How I do this? I manually tried unset($this->db[1]) but it did not work.

Code used

$this->db = json_decode(file_get_contents(self::DB_PATH), true);
$index_num = 0;
foreach($this->db as $url) {
$index_num++;
if($url['ALIAS'] == $this->alias) {
unset($url[$index_num]);
}
}

Thanks for your answers.

    
asked by Derek Nichols 31.07.2017 в 01:09
source

1 answer

0

here your code in which I corrected the error, and a partner noticed, only that he did not dare to correct it

$this->db = json_decode(file_get_contents(self::DB_PATH), true);
$index_num = 0;
$aux=$this->db;//$aux innecesario
foreach($aux as $key => $url) {

     if($url['ALIAS'] == $this->alias) {
          unset($this->db[$key]);
          }

     $index_num++;//innecesario,
     }
unset($aux);

Or to not occupy so much memory for a moment:

$this->db = json_decode(file_get_contents(self::DB_PATH), true);
$index_num = 0;
$aux=[];
foreach($this->db as $key => $url) {

     if($url['ALIAS'] == $this->alias) {
                 $aux[]=$key;
          }


    }
 foreach($aux as $index){unset($this->db[$index]);}    

The other is to use array_filter:

link

    
answered by 31.07.2017 в 01:54