如何将PHP多维数组转换为Python字典格式的字符串?将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字典格式的字符串?将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字典,你可能需要使用JSON,因为这两种语言理解它(尽管你需要安装的东西像simpleJSON为Python)。
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}}')
由于这个问题偶尔仍然受到关注,为了澄清,Python 2+ [有内置的json库](https:// docs.python.org/2/library/json.html)。 – kungphu
你应该实现你想要使用json_encode()
。 Python的符号是非常相似的,因此它应该满足您的需求:
echo json_encode($myarray);
你的阵列应该是这样的Python:
my_array = {
'a1': {
'29b': '',
'29a': ''
},
'a2': {
'29b': '',
'29a': ''
}
}
它的工作原理为你的预期?
这里是基于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)
答案评论和我的解决方案,使你的意思,你要打印出一个PHP多维数组的格式,好像它是一个Python多串维数组? –
是的,我想将数组传递给python脚本,做进一步的分析。我需要将它格式化为一个字符串,以便python通过'sys.argv'接受它。 – user602599