简体   繁体   English

如何通过MySQL表将Python列表转换为PHP数组

[英]How to convert a Python List to a PHP array via a MySQL table

I have inherited a MySQL database where one of the fields in a table returns a string that was once a Python list so I get something like this: 我继承了一个MySQL数据库,在该数据库中,表中的一个字段返回一个曾经是Python列表的字符串,因此我得到如下信息:

$test = "[u'Person 1', u'Person 2']";

What is the cleanest/easiest/best/simplest (I'm not sure how to phrase this) to get this data back into an array in PHP? 什么是最干净/最容易/最好/最简单的(我不确定该如何表述)才能使这些数据返回PHP中的数组? I am using PHP4 but I could upgrade to PHP5.4 if necessary. 我正在使用PHP4,但如有必要,我可以升级到PHP5.4。

I don't have much experience programming in PHP and my first thought was to do something like this: 我没有使用PHP进行编程的丰富经验,我的第一个念头是做这样的事情:

$new = explode(",",$test);

This kind of works but it would need cleaning up afterwards (for instance each element of the array has at least u' in front of it) and is obviously fragile if any of the elements contain a comma. 这种类型的工作,但是之后需要清理(例如,数组的每个元素前面至少都有u'),并且如果其中任何一个元素包含逗号,则显然很脆弱。

Is there a cleaner/easier/better/simpler way of doing this? 有没有更清洁/更容易/更好/更简单的方法?

Your best bet is to write a Python script that updates the mysql datastore with JSON, which can be easily parsed by just about every language out there. 最好的选择是编写一个Python脚本,以JSON更新mysql数据存储,几乎所有语言都可以轻松地对其进行解析。 ( as @Hugo Dozois noted ] (如@Hugo Dozois指出的]

Personally, I wouldn't try to read this in PHP. 就个人而言,我不会尝试在PHP中阅读。 The example you showed has 2 unicode strings in a flat list... but you're likely going to run into more issues and edge cases as time goes on. 您显示的示例在平面列表中有2个unicode字符串...但是随着时间的流逝,您可能会遇到更多的问题和极端情况。 You might have some unicode strings, other byte strings, some numbers... possibly even nested lists or dicts. 您可能会有一些unicode字符串,其他字节字符串,一些数字...甚至可能是嵌套列表或字典。

If you didn't inherit it, and were 100% sure of what's going on - then sure, you could parse stuff. 如果您没有继承它,并且100%知道发生了什么,那么可以解析内容。 But it should take less than 5 minutes to write and run a Python script that converts this to JSON and solves all your problems. 但是编写和运行Python脚本将其转换为JSON并解决所有问题的时间应该少于5分钟。

You could use preg_match_all and do this: 您可以使用preg_match_all并执行以下操作:

$test = "[u'Person 1', u'Person 2']";

preg_match_all('/u\'(.*?)\'/', $test, $matches);

var_dump($matches);

/*
array(2) { 
[0]=> array(2) { 
    [0]=> string(11) "u'Person 1'" 
    [1]=> string(11) "u'Person 2'" } 
[1]=> array(2) { 
    [0]=> string(8) "Person 1" 
    [1]=> string(8) "Person 2" 
    } 
} 
*/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM