简体   繁体   English

用json_encode处理多维数组

[英]dealing multi-dimension arrays with json_encode

Below are the python and php scripts which I have used to pass two matrices for multiplication in python file PHP: 以下是我用来在python文件PHP中传递两个矩阵进行乘法的python和php脚本:

$arr2=array(array(array(1,2),array(3,5)) ,array(array(4,6)array(2,7)))
echo json_encode($arr2);
$rtu= shell_exec("C:/Python27/python 1234.py ".json_encode($arr2));
echo $rtu."\n";

Python: 蟒蛇:

import numpy as np
from numpy.core.umath_tests import matrix_multiply
from numpy import matrix
print json.loads(sys.argv[1])
arr=json.loads(sys.argv[1])
arr1=arr[0]
arr2=arr[1]
print arr1
print arr2
A=np.asmatrix(arr1)
print A
B=np.asmatrix(arr2)
print B
Z1 = matrix_multiply(A,B)

print json.dumps(Z1)

This code is giving correct output for json_encode($arr2) but rest it gives all null.Can anyone pls debug the code? 这段代码为json_encode($ arr2)提供了正确的输出,但是剩下的全部为空。有人可以调试代码吗?

Here is a partial solution. 这是部分解决方案。 I have corrected the python side, which was not working for me as posted. 我已经更正了python方面,该方面对我来说不起作用。

First, I think you should be able to multiply matrices in PHP by writing your own function. 首先,我认为您应该能够通过编写自己的函数在PHP中乘以矩阵。

It can not be as difficult to do matrix multiplication in PHP as it is to deal with JSON, python, and starting a new process and moving data back and forth. 在PHP中进行矩阵乘法并没有像处理JSON,python,启动新进程以及来回移动数据那样困难。

There is an unmaintained PHP library for matrix multiplication at http://pear.php.net/package/Math_Matrix http://pear.php.net/package/Math_Matrix上有一个无需维护的用于矩阵乘法的PHP库。

Ok, so if you want to do it this Rube-Goldberg-ish way here is the corrected python code. 好的,因此,如果您要执行此操作,请使用经过修正的python代码。 It needed imports for json and sys, and .tolist() to deal with getting json to encode the matrix result (json won't encode matrix as-is because it isn't a simple array). 它需要json和sys的导入,以及.tolist()来处理让json对矩阵结果进行编码(json不会按原样对矩阵进行编码,因为它不是简单的数组)。 I discarded the unit test library for numpy.matrix in favor of using the overloaded * instead of matrix_multiply. 我放弃了numpy.matrix的单元测试库,转而使用重载*而不是matrix_multiply。

#!/usr/bin/python
import json
import sys
import numpy as np
from numpy import matrix
print json.loads(sys.argv[1])
arr=json.loads(sys.argv[1])
arr1=arr[0]
arr2=arr[1]
print arr1
print arr2
A=np.asmatrix(arr1)
print A
B=np.asmatrix(arr2)
print B
Z1 = A*B
print Z1
print json.dumps(Z1.tolist())

This is a test prototype. 这是一个测试原型。 For a "production" version you should delete all of the prints except the last one. 对于“生产”版本,应该删除除最后一张以外的所有打印。

Test run: 测试运行:

./matrix_multiply.py "[[[2,0],[0,1]],[[1,3],[2,4]]]"
[[[2, 0], [0, 1]], [[1, 3], [2, 4]]]
[[2, 0], [0, 1]]
[[1, 3], [2, 4]]
[[2 0]
 [0 1]]
[[1 3]
 [2 4]]
[[2 6]
 [2 4]]
[[2, 6], [2, 4]]

looks fine. 看起来不错。

I haven't written any PHP in over 10 years, so I will leave that part to someone else. 我已经十多年没有写PHP了,所以我将把这部分留给别人。

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

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