我想刪除從JSON數組中的元素用PHP刪除JSON對象形式陣列用PHP
[{"userid":"20"},{"userid":"17"},{"userid":"18"}]
我想使這樣說,這
[{"userid":"20"},{"userid":"18"}]
我想刪除從JSON數組中的元素用PHP刪除JSON對象形式陣列用PHP
[{"userid":"20"},{"userid":"17"},{"userid":"18"}]
我想使這樣說,這
[{"userid":"20"},{"userid":"18"}]
首先解析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);
這是輸出'{ 「0」:{ 「用戶id」 :「20」},「2」:{「userid」:「18」}}'但我不想那個鍵[** 0,2 **] –
@AnaJentel檢查我的答案。它工作正常。 – Spectarion
我知道它的工作原理,但我不想顯示所有對象的0,2個鍵 –
如果知道元素索引:
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));
http://php.net/unset – Kaylined