Monday, May 13, 2013

CF Returnformat=json to php Array

So we have a client that wants data returned from our database.

We have CF8 here and building a CFC to dump a query based on some variables was pretty easy.
Define query arguments and return as Query then they say returnformat=json and us CF developers are done.
But as we all know in order to save bandwidth CF does an array of 2 COLUMNS and DATA which contains arrays of data.

This is smart b/c god knows we don't want 4000 foreign_table_key for each integer in the data. But those php developers get a bit frustrated. So I did it for them
function convertColdFusionJSONtoArray($jsonObject) 
    { 
        $s = json_decode($jsonObject, true); 
        // check valid object 
        if(!array_key_exists('COLUMNS', $s) && !array_key_exists('DATA', $s))
  { 
            // put error trapping here 
            $php_errormsg('invalid coldfusion object passed to convertColdFusionJSONtoArray');
 echo $php_errormsg; 
        }
        $returnArray = array(); 
        //Loops through serialObj and matches the columns 
    
        for ($i=0; $i <= count($s['DATA']) -1; $i++){
            $temp = array(); 
            for($j=0; $j < count($s['COLUMNS']); $j++)
            { 
               $temp[$s['COLUMNS'][$j]] = $s['DATA'][$i][$j]; 
            } 
            // save the new row with column names 
            array_push($returnArray, $temp); 
        } 
        return $returnArray; 
    }
So there you have it.

 BTW thanks to: Arlo Carreon for his his Javascript version of the same thing: Click the link to view.