我試圖從 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);
這將兩個串列作為一個字串陣列。
(array(2) { [0]=> string(9) "[1, 2, 3]" [1]=> string(9) "[4, 5, 6]")
使用
$output = json_decode(exec("test.py", $return), true);
var_dump($output);
只給出第二個串列作為陣列。
print(json.dumps([list1,list2]))在 Python 中使用將兩個串列作為單個字串。
如何在 PHP 中將多個串列作為陣列獲取?或者有沒有更好的方法來決議 PHP 中的串列?
uj5u.com熱心網友回復:
你把事情搞混了。您的第一個 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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/346085.html
