我的json喜欢这样:
[{"id": 1, "name": "xkCT0QUAK7alZkYkbrLUfxoYyn9aXMh2kyCZeYFW.jpeg"},
{"id": 2, "name": "9Tg1QLJGiHPC39KP20iOgy3cYQSXOllJTEBGPcF7.jpeg"},
{"id": 3, "name": "fWEfhpRkfy44lqC3Ro1etJKmOOkMXnLJLT4ncS6x.png"}]
我有变量$id
如果$id = 2
,则会删除包含id = 2
如果$id = 3
,则会删除包含id = 3
例如,它将删除具有id = 2
上面的json是这样的:
[{"id": 1, "name": "xkCT0QUAK7alZkYkbrLUfxoYyn9aXMh2kyCZeYFW.jpeg"},
{"id": 2, "name": "fWEfhpRkfy44lqC3Ro1etJKmOOkMXnLJLT4ncS6x.png"}]
删除后,其ID将被重新排序
我该怎么做?
答案 0 :(得分:2)
示例输入:
$json='[{"id": 1, "name": "xkCT0QUAK7alZkYkbrLUfxoYyn9aXMh2kyCZeYFW.jpeg"},
{"id": 2, "name": "9Tg1QLJGiHPC39KP20iOgy3cYQSXOllJTEBGPcF7.jpeg"},
{"id": 3, "name": "fWEfhpRkfy44lqC3Ro1etJKmOOkMXnLJLT4ncS6x.png"}]';
$id=2;
方法(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);
输出:
'[{"id":1,"name":"xkCT0QUAK7alZkYkbrLUfxoYyn9aXMh2kyCZeYFW.jpeg"},
{"id":2,"name":"fWEfhpRkfy44lqC3Ro1etJKmOOkMXnLJLT4ncS6x.png"}]'