How can I remove json element by sub json value?
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 encodevar_export($input);
Output:
'[{"id":1,"name":"xkCT0QUAK7alZkYkbrLUfxoYyn9aXMh2kyCZeYFW.jpeg"}, {"id":2,"name":"fWEfhpRkfy44lqC3Ro1etJKmOOkMXnLJLT4ncS6x.png"}]'