8

我对 php 很陌生,我一直在花一些时间来理解如何将参数从 Python 传递给 php,反之亦然。我现在知道如何传递单个变量,但我仍然卡住,似乎无法找到这个问题的答案:

Php 调用返回字符串列表的 Python 脚本(该部分有效)。我想在 php.ini 中处理这个列表。

当我尝试:

print mylist

在 myscript.py 中,然后:

$result = exec('python myscript.py')

看起来 php 将 $result 理解为单个字符串(我同意这是有道理的)。

我知道也许 json 可以提供帮助,或者我需要在 python 中使用字典而不是列表。但是我无法弄清楚到底如何。

如果有人可以提供帮助,将不胜感激!谢谢!

4

4 回答 4

13

例如:

我的脚本.py

import json

D = {'foo':1, 'baz': 2}

print json.dumps(D)

我的脚本.php

<?php 

$result = json_decode(exec('python myscript.py'), true);
echo $result['foo'];
于 2013-06-21T12:49:05.500 回答
2

You're using stdin / stdout to transfer the data between the programs, that means you'll have to encode your structure somehow in order to let your receiving program parse the elements.

The simplest thing would be to have python output something like a comma separated list

Adam,Barry,Cain

and use

$result = explode(exec('python myscript.py'));

on the php side to turn your string data back into an array.

If the data is unpredictable (might contain commas) or more structured (more than just a simple list) then you should go for something like json as suggested by Krab.

于 2013-06-21T13:28:53.510 回答
1

显然你的问题具有误导性。被重定向到这里,认为这是将 python 列表转换为 php 数组的解决方案。

为想要将列表转换为 php 数组的人发布一个简单的解决方案。

// Sample python list 
$data = '[["1","2","3","4"],["11","12","13","14"],["21","22","23","24"]]';

// Removing the outer list brackets
$data =  substr($data,1,-1);

$myArr = array();
// Will get a 3 dimensional array, one dimension for each list
$myArr =explode('],', $data);

// Removing last list bracket for the last dimension
if(count($myArr)>1)
$myArr[count($myArr)-1] = substr($myArr[count($myArr)-1],0,-1);

// Removing first last bracket for each dimenion and breaking it down further
foreach ($myArr as $key => $value) {
 $value = substr($value,1);
 $myArr[$key] = array();
 $myArr[$key] = explode(',',$value);
}

//Output
Array
(
[0] => Array
    (
        [0] => "1"
        [1] => "2"
        [2] => "3"
        [3] => "4"
    )

[1] => Array
    (
        [0] => "11"
        [1] => "12"
        [2] => "13"
        [3] => "14"
    )

[2] => Array
    (
        [0] => "21"
        [1] => "22"
        [2] => "23"
        [3] => "24"
    )

)
于 2015-07-22T13:14:22.940 回答
0
$str = "[u'element1', u'element2', 'element3']";

$str = str_replace( array("u'", "[", "]"), array("'", ""), $str );
$strToPHPArray = str_getcsv($str, ",", "'");
print_r( $strToPHPArray );

输出

Array
(
    [0] => element1
    [1] => element2
    [2] => element3
)
于 2018-09-12T11:09:37.717 回答