View Single Post
Old 12-14-2007, 05:54 PM   #3 (permalink)
Salathe
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 1,393
Thanks: 5
Salathe is on a distinguished road
Default

I think that I've come up with a function which will do this conversion properly. I've done a bunch of tests against answers which I know are correct (from the Google Charts docs) and everything appears ok. If there is something broken, at least you'll have a starting point to push forwards from.

So, below is the function and the tests used to see if it works or not.

php Code:
<?php


// This function converts an integer (0 < i <= 4095)
// into the 'extended' format for Google Charts data.
function convert($iValue)
{
    static $szBase, $iBaseLen;
   
    // Initialise static variables only once
    isset($szBase)   or $szBase   = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.';
    isset($iBaseLen) or $iBaseLen = strlen($szBase);
   
    // If an invalid value is provided, return 'missing value'
    if (!is_int($iValue) or $iValue < 0 or $iValue > 4095)
    {
        return '__';
    }
   
    // Process the integer value into the new 'base' and return
    return $szBase[(int) ($iValue / $iBaseLen)] . $szBase[$iValue % $iBaseLen];
}


// Set up some test cases to which we know the expected results
$aExpected = array('AA', 'AZ', 'Aa', 'Az', 'A0', 'A9', 'A-', 'A.',
                   'BA', 'BZ', 'Ba', 'Bz', 'B0', 'B9', 'B-', 'B.',
                   '.A', '.Z', '.a', '.z', '.0', '.9', '.-', '..');
                   
$aTests    = array(0,    25,   26,   51,   52,   61,   62,   63,
                   64,   89,   90,   115116125126127,
                   4032, 4057, 4058, 4083, 4084, 4093, 4094, 4095);

// Run the test cases
$aResults = array_map('convert', $aTests);

// Output the result for each of the tests
header('Content-Type: text/plain');
foreach ($aExpected as $iKey => $szExpected)
{
    $szResult = ($aResults[$iKey] === $szExpected ? 'passed' : '***** FAILED, should be: ' . $szExpected);
    printf("%4d -> %s %s\n", $aTests[$iKey], $aResults[$iKey], $szResult);
}

For me, that test page returns the following output:
Code:
   0 -> AA passed
  25 -> AZ passed
  26 -> Aa passed
  51 -> Az passed
  52 -> A0 passed
  61 -> A9 passed
  62 -> A- passed
  63 -> A. passed
  64 -> BA passed
  89 -> BZ passed
  90 -> Ba passed
 115 -> Bz passed
 116 -> B0 passed
 125 -> B9 passed
 126 -> B- passed
 127 -> B. passed
4032 -> .A passed
4057 -> .Z passed
4058 -> .a passed
4083 -> .z passed
4084 -> .0 passed
4093 -> .9 passed
4094 -> .- passed
4095 -> .. passed
Salathe is offline  
Reply With Quote
The Following 2 Users Say Thank You to Salathe For This Useful Post:
Karl (12-14-2007), sketchMedia (12-15-2007)