【问题标题】:Pass multiple lists from Python to a PHP array?将多个列表从 Python 传递到 PHP 数组?
【发布时间】:2021-12-17 06:15:44
【问题描述】:

我试图从 python 脚本获取多个列表到 PHP。离开这个问题Passing a Python list to php,我正在使用 Json。

Python:

list1 = [1,2,3]
list2 = [4,5,6]
print(json.dumps(list1))
print(json.dumps(list2))

对于 PHP,我尝试了多种方法:

json_decode(exec("test.py", $return), true);

var_dump($return);

这会将两个列表作为字符串数组。

(数组(2) { [0]=> 字符串(9) "[1, 2, 3]" [1]=> 字符串(9) "[4, 5, 6]")

使用

$output = json_decode(exec("test.py", $return), true);

var_dump($output); 

仅将第二个列表作为数组给出。

在 Python 中使用 print(json.dumps([list1,list2])) 会将两个列表作为单个字符串。

如何在 PHP 中获取多个列表作为数组?或者有没有更好的方法来解析 PHP 中的列表?

【问题讨论】:

  • 你应该可以在 python 中做到这一点:print([list1, list2])
  • @C_Z_ 这只是给出一个与print(json.dumps([list1,list2]))相同的长字符串

标签: python php


【解决方案1】:

你把事情搞混了。 您的第一个 python 示例生成 2 个有效的 json 字符串,它们一起是无效的 json。

然后exec 返回输出的最后行并将每一行作为一个条目存储在第二个参数 ($return) 中。

所以你的python应该是这样的:

list1 = [1,2,3]
list2 = [4,5,6]
# Print one line of json
print(json.dumps([list1, list2]))

还有 PHP:

$output = exec("test.py");
$data = json_decode($output, true);

// OR
$output = [];
exec("test.py", $output);

$data = json_decode($output[0], true);

【讨论】:

  • 谢谢,你的第二个例子对我有用。现在每个列表都可以通过 output[] 作为数组访问
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-16
  • 2021-04-16
  • 2011-07-11
  • 2023-03-27
  • 2012-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多