This is a discussion on case insensitive associative array (tolerant dictionary) within the PHP Language forums, part of the PHP Programming Forums category; Can anyone think of a way to make array keys case insensitive? An option on any recent PHP would be ...
|
|||||||
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
|
|||
|
Can anyone think of a way to make array keys case insensitive?
An option on any recent PHP would be to convert all array keys to lowercase using the standard array_change_key_case() function. As it turns out, I'm stuck on a PHP 4.1.3 system, so that function is not available to me. Can anyone think of an efficient way to write my own version of this function? Can I edit keys in place without copying the values, or will I have to copy the entire array (both keys and values)? Background: I have some database access code that must work with multiple databases. The problem is that some databases return their column metadata in all caps no matter how the SELECT statement or table schema defined it. http://www.oracle.com/technology/tec...ml#assocarrays The following PHP-PEAR code fails on Oracle: $row = $this->db->getAll ("SELECT my_id, my_string, my_flag FROM my_table WHERE my_id=" . $key_id); print $row['my_id']; print $row['my_string']; print $row['my_flag']; Istead, you must access the row record array like this: print $row['MY_ID']; print $row['MY_STRING']; print $row['MY_FLAG']; This would be a simple problem if I only needed to deal with Oracle. I would just add strtoupper() all my keys before using them. But then this code would not work on MySQL and PostgreSQL. I could write a wrapper function like this: function aa_get_i($aa, $key) { if ( isset($aa[$key]) ) return $aa[$key]; return $aa[strtoupper($key)]; } But I was hoping there is something more clever that I could do. Also this isn't strictly a case insensitive array get. If I find some other database that converts to all lowercase then I have to add another test. Yours, Noah Spurrier |
|
|||
|
You can always just loop through the array, and build another array as
you go with lowercase keys. This might not be the most elegant way, but it's pretty straightforward and easy. This should work if you have an array of scalar values, or a 2-dimensional array also: <?php # untested $new_ar = array(); foreach ($old_ar as $key => $val) { if (!is_array($val)) { $new_ar[strtolower($key)] = $val; } else { $new_ar[strtolower($key)] = array(); foreach ($val as $subkey => $subval) { $new_ar[strtolower($key)][strtolower($subkey)] = $subval; } } } ?> |