How to remove json element by sub json value?
My json is like this:
[{"id": 1, "name": "xkCT0QUAK7alZkYkbrLUfxoYyn9aXMh2kyCZeYFW.jpeg"},
{"id": 2, "name": "9Tg1QLJGiHPC39KP20iOgy3cYQSXOllJTEBGPcF7.jpeg"},
{"id": 3, "name": "fWEfhpRkfy44lqC3Ro1etJKmOOkMXnLJLT4ncS6x.png"}]
I have a variable $id
if $id = 2
, it will remove json fromid = 2
if $id = 3
, it will remove json fromid = 3
For example, it will remove json from id = 2
Json above for this:
[{"id": 1, "name": "xkCT0QUAK7alZkYkbrLUfxoYyn9aXMh2kyCZeYFW.jpeg"},
{"id": 2, "name": "fWEfhpRkfy44lqC3Ro1etJKmOOkMXnLJLT4ncS6x.png"}]
When deleted, its ID will be sorted back
How can i do this?
+3
source to share
1 answer
Input example:
$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"}]'
+2
source to share