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

-2 投票
3 回答
10070 浏览
提问于 2025-04-17 10:40

如何将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 个回答

1

这是我根据kungphu的评论和RichieHindle在如何快速将字典的键和值从`unicode`转换为`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)
2

你可以通过使用 json_encode() 来实现你想要的效果。Python 的写法也很相似,所以应该能满足你的需求:

echo json_encode($myarray);

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

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

这样做是否达到了你的预期效果?

6

如果你需要把一个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}}')

撰写回答