Get Keys Function
The getKeys function in SwartzDB allows users to retrieve all unique keys (columns) present in a database file, even if some columns exist only in specific records.
How getKeys Works
🔹 Reads the database file and extracts all possible keys from the stored data.
🔹 Recursively scans through nested arrays, ensuring no key is left out.
🔹 Removes duplicate keys, so each key appears only once in the output.
🔹 Returns a list of column names that exist in the dataset.
Why is getKeys Useful?
✅ Handles inconsistent data structures – Some records might have extra fields, and this function ensures visibility of all columns.
✅ Helps with dynamic queries – Knowing all available keys allows users to filter, search, or modify data efficiently.
✅ Supports nested structures – Works with multi-level arrays, extracting keys in a structured format.
Example Usage
Database Data
[
{"id": 1, "name": "Alice", "age": 25, "city": "New York"},
{"id": 2, "name": "Bob", "age": 30},
{"id": 3, "name": "Charlie", "country": "USA"}
]
Calling getKeys
$keys = $sdb->getKeys("users");
print_r($keys);
Output
["id", "name", "age", "city", "country"]
- The
cityandcountrycolumns were created only for some records, butgetKeysensures they are visible.
Conclusion
getKeys provides a complete overview of all columns in the database, making it easier to work with dynamic datasets. This function is essential for users who need to explore, analyze, or manipulate data efficiently.