【问题标题】:Convert PHP array to a string in Python dictionary format将 PHP 数组转换为 Python 字典格式的字符串
【发布时间】:2012-02-14 16:03:32
【问题描述】:

如何将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) "" } }

【问题讨论】:

  • 那么你的意思是要把一个php多维数组打印成一个字符串格式,就好像它是一个python多维数组一样?
  • 是的,我想将数组传递给python脚本,做进一步的分析。我需要将其格式化为字符串,以便 python 通过sys.argv 接受它

标签: php python arrays function dictionary


【解决方案1】:

如果您需要通过文本将 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}}')

【讨论】:

【解决方案2】:

您应该使用json_encode() 来实现您想要的。 Python 表示法非常相似,因此应该可以满足您的需求:

echo json_encode($myarray);

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

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

它是否按您的预期工作?

【讨论】:

    【解决方案3】:

    这是我的解决方案,基于 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)
    

    【讨论】:

      猜你喜欢
      • 2021-08-21
      • 1970-01-01
      • 2019-01-08
      • 2022-07-24
      • 1970-01-01
      • 1970-01-01
      • 2020-09-16
      • 2014-02-19
      • 2012-03-20
      相关资源
      最近更新 更多