Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Python dictionary to PHP array (See related posts)

Pass any python dictionary into convertArray.
It will return an array that PHP can read.

Example:
>>> convertArray({"One":1, "Two":[2,"Two"], "Three":[{"ThreeAgain":[3,3,3]} ,[1,2,3], "Three"]})

Returns: array('Three'=>array(array('ThreeAgain'=>array(3, 3, 3)), array(1, 2, 3), 'Three'), 'Two'=>array(2, 'Two'), 'One'=>1)


## Converts a python dictionary to a php array.
def convertArray(arr):
        ret = ""
        list = []
        
        if isinstance(arr, type([]) ):                ## If the instance is an array
                
                for ele in arr:
                        if isinstance(ele, ( type([]), type({})) ):  ## If the instance is an array
                                list.append( convertArray(ele))                                 ## recursive it
                        
                        elif isinstance(ele, (type(1), type(1.0))): 
                                list.append(str(ele))           ## if an int or float, no quotes
                        else:
                                list.append("'%s'" % str(ele))
        
        elif isinstance(arr, type({}) ):                ## If the instance is an array
                for (k,v) in arr.items():
                        item = "'" + str(k) + "'=>"
                        if isinstance(v, ( type([]), type({})) ):
                                item += ( convertArray(v))
                        else:
                                if isinstance(v, (type(1), type(1.0))):   
                                        item += (str(v))           ## if an int or float, no quotes
                                else:
                                        item += ("'%s'" % str(v))
                        list.append(item)
        else:
                raise NameError, "Error - neither a array or a dictionary was passed to this function"
        
        
        if len(list) > 0:
                ret = "array(" + ", ".join(list) + ")"
        else:
                ret = "array()"
                
        return ret

You need to create an account or log in to post comments to this site.


Related Posts