Backend Development
PHP Tutorial
PHP/CodeIgniter: Efficiently delete specified elements from the database JSON array
PHP/CodeIgniter: Efficiently delete specified elements from the database JSON array

Overview: Managing JSON array data in the database
In web development, sometimes we need to store multiple associated IDs or configuration information in one database field. Serializing this information into a JSON array is a common and flexible practice. For example, a user may belong to multiple groups, and we can store the IDs of these groups in the form of a JSON array in the personEmailGroup field of the person table, such as ["1", "2", "4"]. This approach simplifies the database structure, but it also brings the challenge of how to modify the contents of these JSON arrays efficiently, especially when we need to delete a specific element in the array.
Challenge: Remove specified ID from JSON array
When we need to delete a specific ID (such as "4") from a JSON array such as ["1", "2", "4"] and make it become ["1", "2"], it is not feasible to directly operate the JSON string. We need a process to:
- Read JSON string from database.
- Convert it into a PHP-operable data structure (array).
- Remove target element from PHP array.
- Reconvert the modified PHP array into a JSON string.
- Update database fields.
A common mistake is to try to unset an array element directly by its value. This may work in an associative array, but in an indexed array, unset requires the key (index) of the element, not the value itself.
Solution: use json_decode, array_search and unset
The core of solving this problem lies in correctly handling element deletion of PHP arrays. The following are detailed steps and implementation under the CodeIgniter framework.
1. Get JSON string from database
First, we need to query the personEmailGroup field value that stores the JSON array from the database based on personId.
// Get request parameter $personId = $this->input->post("personId"); // Person ID with multiple mailbox groups
// Query the specified person's email group JSON string $getEmailGroupJson = $this->db->where("personId", $personId)->get('person')->row("personEmailGroup");
2. Decode JSON string into PHP array
After obtaining the JSON string, use the json_decode() function to convert it into a PHP array.
$getEmailGroupArray = json_decode($getEmailGroupJson);
At this time $getEmailGroupArray may be a PHP array like [1, 2, 4].
3. Find and remove the target element
This is a critical step. What we need to delete is not the Nth element in the array, but the element with the value $processToGroupId.
- Use the array_search($value, $array) function to find the key (index) of $value in $array.
- array_search will return the corresponding key if found, or false if not found.
- Once the key is found, you can use unset($array[$key]) to remove the element.
$processToGroupId = $this->input->post("groupId"); // Group ID to be deleted
// Make sure $getEmailGroupArray is an array, even if the database stores empty values or invalid JSON
if (!is_array($getEmailGroupArray)) {
$getEmailGroupArray = [];
}
// Find the index of the group ID to be deleted in the array if (($key = array_search($processToGroupId, $getEmailGroupArray)) !== false) {
// If the corresponding ID is found, delete the element through the index unset($getEmailGroupArray[$key]);
}
Important note: When array_search returns 0, 0 == false is true, which may lead to misjudgment. Therefore, strict comparison !== false must be used to ensure accurate determination of whether the element is found.
4. Re-encode modified PHP array into JSON string
After the elements are removed, the modified PHP array is re-encoded into a JSON string using the json_encode() function for storage back into the database.
$updatedEmailGroupJson = json_encode($getEmailGroupArray);
5. Update database
Finally, use CodeIgniter's update method to save the new JSON string back to the database.
$data = array(
"personEmailGroup" => $updatedEmailGroupJson,
);
$process = $this->db->where("personId", $personId)->update("person", $data);
// Process the update result if ($process) {
$dataJson['status'] = true;
echo json_encode($dataJson);
} else {
$dataJson['status'] = false;
echo json_encode($dataJson);
}
Complete sample code
Combining the above steps, the following is the complete CodeIgniter PHP code to delete JSON array elements:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Person_model extends CI_Model {
public function deleteGroupFromPersonEmailGroup() {
// 1. Get the request parameter $personId = $this->input->post("personId"); // Person ID with multiple mailbox groups
$groupIdToDelete = $this->input->post("groupId"); // Group ID to be deleted
// 2. Query the email group JSON string of the specified person from the database // Note: The unnecessary JSON_CONTAINS filtering in the original question is removed here, because we only need to get the entire JSON string $getEmailGroupJson = $this->db->where("personId", $personId)->get('person')->row("personEmailGroup");
// 3. Decode JSON string into PHP array // Ensure that even if the database field is empty or contains invalid JSON, you can get an operable array $getEmailGroupArray = json_decode($getEmailGroupJson);
if (!is_array($getEmailGroupArray)) {
$getEmailGroupArray = []; // If decoding fails or is not an array, initialize to an empty array}
// 4. Find and remove the target element // Use array_search to find the index of the group ID to be deleted in the array if (($key = array_search($groupIdToDelete, $getEmailGroupArray)) !== false) {
// If the corresponding ID is found, delete the element through the index unset($getEmailGroupArray[$key]);
}
// 5. Re-encode the modified PHP array into a JSON string // Make sure the array indices are contiguous before re-encoding, although this is usually not a problem for simple numeric arrays,
// But you can use array_values() to reset the index if needed.
// $getEmailGroupArray = array_values($getEmailGroupArray);
$updatedEmailGroupJson = json_encode($getEmailGroupArray);
// 6. Update the database $dataToUpdate = array(
"personEmailGroup" => $updatedEmailGroupJson,
);
$process = $this->db->where("personId", $personId)->update("person", $dataToUpdate);
// 7. Return the operation result $response = [];
if ($process) {
$response['status'] = true;
$response['message'] = 'The group ID was successfully deleted and updated. ';
} else {
$response['status'] = false;
$response['message'] = 'Group ID deletion failed or database update failed. ';
}
echo json_encode($response);
}
}
Things to note and best practices
- Error handling: In actual applications, json_decode() may return null due to invalid JSON string. Before operating on an array, you should check its return value to make sure it is a valid array.
- Data types: array_search considers data types when comparing. If the ID stored in the database is a string (such as "1"), and the $groupIdToDelete you pass in is an integer (such as 1), you may need to perform type conversion, or use the third parameter strict to true in array_search for strict comparison and ensure that the types are consistent.
- Empty array handling: Consider the situation when the personEmailGroup field is empty or is an empty array after decoding. The above code has been added to the !is_array($getEmailGroupArray) check to ensure that it can be safely initialized to an empty array.
- Database design: Although it is convenient to store JSON arrays in a single field, for scenarios that require frequent querying, filtering, or aggregation of these "sub-elements", it is more recommended to use traditional many-to-many relational tables (for example, create a person_email_groups intermediate table containing person_id and group_id). This takes better advantage of the database's indexing and query optimization capabilities.
- Input validation: Data obtained from user input (such as $this->input->post()) is always validated and sanitized to prevent SQL injection and XSS attacks.
- Index reset: The unset() operation will retain the original array keys. If you delete an intermediate element, the keys of the array will no longer be contiguous. In some cases, this may not be a problem. But if you need to use continuous indexing later (for example, you need a compact list), you can use $getEmailGroupArray = array_values($getEmailGroupArray); to reset the numeric index of the array.
Summarize
Through the above method, we can safely and efficiently delete specified elements from the JSON array field stored in the database in PHP and CodeIgniter framework. The core is to understand the correct usage of json_decode, array_search and unset, and combine it with CodeIgniter's database operation function to realize data reading, modification and write-back. When choosing a storage solution, you should also weigh the convenience of JSON fields and the advantages of traditional relational tables in complex query scenarios.
The above is the detailed content of PHP/CodeIgniter: Efficiently delete specified elements from the database JSON array. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20518
7
13631
4
Instantiation mechanism and reflection application of PHP attributes
Mar 13, 2026 pm 12:27 PM
PHP properties do not automatically instantiate their class constructors when declared. They are essentially metadata attached to code elements and need to be explicitly read and instantiated through PHP's reflection API in order to trigger the execution of their constructors. Understanding this mechanism is critical to correctly utilizing properties to implement advanced functionality such as framework routing, validation, or ORM mapping.
How to display hospital/center name instead of ID in patient query results
Mar 13, 2026 pm 12:45 PM
This article explains in detail how to use SQL table connections to replace the originally displayed hospital ID (h_id) with the corresponding hospital or center name when querying patient data to improve data readability and user experience.
PHP gRPC client JWT authentication practice guide
Mar 14, 2026 pm 01:00 PM
This article details how to correctly configure JWT (JSON Web Token) for authentication in the PHP gRPC client. The core is to set the request metadata in the standard Authorization: Bearer format through the update_metadata callback function to ensure that the server can correctly parse and verify the client's identity, thereby avoiding common authentication errors.
How to batch extract the values of all keys with the same name (such as 'id') in a JSON object in PHP
Mar 14, 2026 pm 12:42 PM
This article explains in detail how to use json_decode() and array_column() to efficiently extract all values of specified keys (such as id) in nested JSON data at all levels, avoiding manual traversal and taking into account performance and readability.
How to append corresponding value to the end of each subarray of PHP array
Mar 14, 2026 pm 12:51 PM
This article describes how to append the values of a one-dimensional index array to the end of each sub-array of another two-dimensional array in order, solving alignment problems caused by index offsets (such as $array2 starting from key 1), and providing a safe and readable implementation solution.
Tutorial on flattening nested arrays into a single array in PHP
Mar 13, 2026 am 02:57 AM
This tutorial details how to flatten a nested array structure containing multiple sub-arrays into a single array in PHP. This can be achieved efficiently and concisely by utilizing PHP's array_merge function combined with the array unpacking operator (...) to extract all internal elements into a top-level array, suitable for processing collections or grouped data.
PHP runtime getting and monitoring script maximum memory limit (bytes)
Apr 01, 2026 am 06:42 AM
This article aims to guide PHP developers on how to accurately obtain the maximum memory limit (in bytes) of a script at runtime, and combine it with real-time memory usage for effective monitoring. By parsing the memory_limit configuration string and using built-in functions, an early warning mechanism for memory consumption is implemented to avoid fatal errors caused by memory overflow.
Solving the problem of garbled Arabic characters inserted into MySQL by PHP applications: Comprehensive UTF-8 encoding guide
Mar 05, 2026 am 10:30 AM
This article aims to solve the problem of garbled characters (appearing as question marks????) when a PHP application inserts Arabic characters into a MySQL database, but the direct insertion through phpMyAdmin displays normally. The core is to ensure that the entire data flow from database, PHP connection, PHP script file to HTML output is uniformly encoded in UTF-8 to avoid data damage caused by inconsistent encoding. The article will provide detailed configuration steps and code examples, and provide guidance on how to verify and handle corrupted data.





