使用php在MySQL数据库中保存不同大小的双数组

I am trying to store the coefficients of a rational function into a MySQL 5.5 database. This is done using PHP 5, which I am rather new to.

In more detail I have two arrays each representing the coefficients of the numerator and denominator polynomial (factored form). The size of both arrays is dynamic between 1 and 10 and if needed I can sort the numbers into any arbitrary order. All numbers are of type double.

Stored in the Database I only have to compare the functions for equality. Which means I only need to figure out if both arrays have the same coefficients (order does not matter). E.g. [1,2,3] and [3,1,2] are the same.

As MySQL does not offer to save arrays directly, I am not sure how to approach this task in the best way.

My current idea, I am yet unsure if feasible, is to sort both arrays in descending order. Then typecast each double to a string of 8 symbols, concatenating all strings. Afterwards I would store that (long) string as VARCHAR. To compare two functions I would compare the numerator and denominator string and if both match, the functions are the same.

A problem I see with that approach is the 'typecasting'. Interpreting a double as 8 characters is pretty crude and I have no idea if the resulting symbols might end the string early or cause any trouble.

Which brings my to my question, does this way work or is there a better way to do it?

Yes, that should work, and is probably a good way to do it.

If you're only checking for equality, you just need to convert to some canonical string representation, and save that in the database. A shorter representation is better for space usage, but making it still human-readable would be nice as well, since that should help with ad-hoc queries and debugging.

Note that order probably does matter for a rational function. Also, if you're dealing with floating-point, you need to watch out for numbers that aren't exactly equal but might be close enough for what you're doing.

A few options:

  • Store two columns, each a comma-delimited list of numbers (with zeroes for missing coefficients in the middle). Put them together with implode.
  • Store one column, containing two comma-delimited lists separates by a / character.
  • Store two VARBINARY columns, each 8 × n bytes long (where n is the number of coefficients). This would be easy in C or Java or perl, in PHP use the pack function.
  • Store one VARBINARY column, format length byte + data + data. Once again, user the pack function.