GetRecordIndexByKey

Databases
Aptilis 1

GetRecordIndexByKey(ArrayName[], Key, Index [, FromWhere])

GetRecordIndexByKey scans a database that has usually been loaded with loadDatabase.
The function returns an index, which you can then use to retrieve a record.

The Key you indicate will be compared to all the fields at the Indexth position in each record. Field indexes start at 0.
To search for multiple matches, you can indicate from which record you want to start. That's the optional FromWhere parameter. The first record also has an index of 0. You must start at 0, and then set the start parameter to (the found index + 1) or stop the search if no match was found.
If no match is found, the function returns -1.
A approximative search can also be done with getRecordIndexByNearKey.

GetAllRecordsByKey and GetAllRecordsByNearKey are more high-level and allow you to retrieve several records directly, in one go.

Return value:
A valid index in the database, -1 otherwise.

Example 1:
a database

"Ferrari","red","100,000","2 seats"
"Mercedes","Blue","50,000","2 seats and a half"
"Clio","green","10,000","Nearly five seats"
"Jaguar","blue","200,000","9 seats"
"Lotus","Silver","250,000","2 seats"

Name of car: field 0
Colour: field 1
Price: field 2
Seats: field 3
We are going to load the database with the loaddatabase function.
This one is made up of 5 records, each with four fields.

Example 2:
Assuming we are on a Windows type machine...

// Load the database into, say, 'db'
// We won't use n in this example
n = loadDatabase(db[], "c:\\databases\\cars\\cars.txt")

// We want to find the record that says 'colour blue'
// The colours are stored in Field 1.
ix = getRecordIndexByKey(db[], "blue", 1)

if ix = -1
print("No record found\n")
else
// First, let's print the index
print("Record found at: ", int(index), "\n")

// Then, just the name of the car
n = getField(db[ix]$, 0) $

print("The ", n$, " is blue\n")

end if

Result:
"Record found at: 1
The Mercedes is blue
See also getField and getAllFields

Example 3:
Here, we search for all the records.

loadDatabase(db[], "c:\\databases\\cars\\cars.txt")

ix = 0
repeat
ix = getRecordIndexByKey(db[], "blue", 1, ix)
if ix <> -1

// Just the name of the car
n = getField(db[ix]$, 0) $

print("The ", n$, " is blue\n")

// Start at the next record, otherwise we would loop indefinetly
ix = ix + 1

end if

until ix = -1

Result:
The Mercedes is blue
The Jaguar is blue

Notes