将PHP数组转换为Python字典格式的字符串

时间:2012-01-20 00:51:55

标签: php python arrays function dictionary

如何将PHP多维数组转换为Python字典格式的字符串?

var_dump($myarray);

array(2) { ["a1"]=> array(2) { ["29b"]=> string(0) "" ["29a"]=> string(0) "" } ["a2"]=> array(2) { ["29b"]=> string(0) "" ["29a"]=> string(0) "" } }

3 个答案:

答案 0 :(得分:5)

如果您需要通过文本将PHP关联数组转换为Python字典,您可能需要使用JSON,因为两种语言都能理解它(尽管您需要为Python安装类似simpleJSON的东西)。

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

示例(显然这需要一些自动工作)......

<?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}}')

答案 1 :(得分:1)

您应该使用json_encode()达到您想要的效果。 Python表示法非常相似,因此它应该满足您的需求:

echo json_encode($myarray);

你的数组在Python中应该是这样的:

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

它是否按预期工作?

答案 2 :(得分:1)

以下是基于kungphu上述评论和RichieHindle在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)
相关问题