我想用php
从json数组中删除一个元素[{"userid":"20"},{"userid":"17"},{"userid":"18"}]
我想让它像那样
[{"userid":"20"},{"userid":"18"}]
答案 0 :(得分:3)
首先解析JSON字符串,然后删除该元素,然后再次对其进行编码:
$array = json_decode('[{"userid":"20"},{"userid":"17"},{"userid":"18"}]');
foreach ($array as $key=>$element) {
if ($element->userid == "17") {
unset($array[$key]);
}
}
$output = json_encode($array);
答案 1 :(得分:1)
如果你知道元素索引:
unset($array[1]); // 1 is the index of element.
如果您不知道元素索引:
// Deserialize the JSON into associative array.
$users = json_decode('[{"userid":"20"},{"userid":"17"},{"userid":"18"}]', true);
// For each user and it's index in array of users.
foreach ($users as $index => $user) {
// If currently iterated user id is equals to 17.
if ($user["userid"] == 17) {
// Remove it from an array of users.
unset($users[$index]);
}
}
// Echo all elements inside an array of users as JSON.
echo json_encode(array_values($users));