简体   繁体   中英

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:

$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?

Here is a partial solution. I have corrected the python side, which was not working for me as posted.

First, I think you should be able to multiply matrices in PHP by writing your own function.

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.

There is an unmaintained PHP library for matrix multiplication at http://pear.php.net/package/Math_Matrix

Ok, so if you want to do it this Rube-Goldberg-ish way here is the corrected python code. 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). I discarded the unit test library for numpy.matrix in favor of using the overloaded * instead of 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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