-2

How to convert PHP multidimensional array to a string in Python dictionary format?

var_dump($myarray);

array(2) { ["a1"]=> array(2) { ["29b"]=> string(0) "" ["29a"]=> string(0) "" } ["a2"]=> array(2) { ["29b"]=> string(0) "" ["29a"]=> string(0) "" } }
juliomalegria
  • 24,229
  • 14
  • 73
  • 89
user602599
  • 661
  • 11
  • 22
  • 1
    So do you mean that you want to print out a php multi-dimensional array as a string formatted as if it were a python multi-dimensional array? – Max Spencer Jan 20 '12 at 01:11
  • yes, I want to pass the array to the python script, to do further analysis. I need to format that as a string in order for python to accept it via `sys.argv` – user602599 Jan 20 '12 at 02:35

3 Answers3

6

If you need to convert a PHP associative array into a Python dictionary via text, you may want to use JSON, since both languages understand it (though you'll need to install something like simpleJSON for Python).

http://www.php.net/manual/en/function.json-encode.php http://simplejson.readthedocs.org/en/latest/index.html

Example (obviously this would need some work to be automatic)...

<?php
$arr = array('test' => 1, 'ing' => 2, 'curveball' => array(1, 2, 3=>4) );
echo json_encode($arr);
?>

# elsewhere, in Python...
import simplejson
print simplejson.loads('{"test":1,"ing":2,"curveball":{"0":1,"1":2,"3":4}}')
kungphu
  • 4,592
  • 3
  • 28
  • 37
  • Since this occasionally still gets attention, to clarify, Python 2+ [has the `json` library built in](https://docs.python.org/2/library/json.html). – kungphu Feb 19 '18 at 05:23
2

You should achieve what you want by using json_encode(). Python notation is very similar, thus it should meet your needs:

echo json_encode($myarray);

Your array should be something like this in Python:

my_array = {
    'a1': {
        '29b': '',
        '29a': ''
    },
    'a2': {
        '29b': '',
        '29a': ''
    }
}

Does it work as you expected?

Tadeck
  • 132,510
  • 28
  • 152
  • 198
1

Here's my solution based on kungphu's comment above and RichieHindle's answer at Fastest way to convert a dict's keys & values from `unicode` to `str`?

import collections, json

def convert(data):
    if isinstance(data, unicode):
        return str(data)
    elif isinstance(data, collections.Mapping):
        return dict(map(convert, data.iteritems()))
    elif isinstance(data, collections.Iterable):
        return type(data)(map(convert, data))
    else:
        return data

import json
DATA = json.loads('{"test":1,"ing":2,"curveball":{"0":1,"1":2,"3":4}}')

print convert(DATA)
Community
  • 1
  • 1
user602599
  • 661
  • 11
  • 22