3

My json like this :

[{"id": 1, "name": "xkCT0QUAK7alZkYkbrLUfxoYyn9aXMh2kyCZeYFW.jpeg"}, 
{"id": 2, "name": "9Tg1QLJGiHPC39KP20iOgy3cYQSXOllJTEBGPcF7.jpeg"}, 
{"id": 3, "name": "fWEfhpRkfy44lqC3Ro1etJKmOOkMXnLJLT4ncS6x.png"}]

I have variable $id

if $id = 2, it will remove json that have id = 2

if $id = 3, it will remove json that have id = 3

For example, it will remove json that have id = 2

The json above to be like this :

[{"id": 1, "name": "xkCT0QUAK7alZkYkbrLUfxoYyn9aXMh2kyCZeYFW.jpeg"}, 
{"id": 2, "name": "fWEfhpRkfy44lqC3Ro1etJKmOOkMXnLJLT4ncS6x.png"}]

When deleted, its id will be sorted back

How can I do it?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
moses toh
  • 12,344
  • 71
  • 243
  • 443

1 Answers1

2

Sample Input:

$json='[{"id": 1, "name": "xkCT0QUAK7alZkYkbrLUfxoYyn9aXMh2kyCZeYFW.jpeg"}, 
{"id": 2, "name": "9Tg1QLJGiHPC39KP20iOgy3cYQSXOllJTEBGPcF7.jpeg"}, 
{"id": 3, "name": "fWEfhpRkfy44lqC3Ro1etJKmOOkMXnLJLT4ncS6x.png"}]';
$id=2;

Method (Demo):

$new_id=0;
$input=json_decode($json,true);
foreach($input as $i=>$a){
    if($a['id']==$id){
        unset($input[$i]);                  // remove the desired subarray
    }else{
        $input[$i]['id']=++$new_id;         // set correct id value (and increment $new_id)
    }
}

$input=json_encode(array_values($input));   // re-index first-level keys & json encode
var_export($input);

Output:

'[{"id":1,"name":"xkCT0QUAK7alZkYkbrLUfxoYyn9aXMh2kyCZeYFW.jpeg"},
  {"id":2,"name":"fWEfhpRkfy44lqC3Ro1etJKmOOkMXnLJLT4ncS6x.png"}]'
mickmackusa
  • 43,625
  • 12
  • 83
  • 136