In your python script do something like
import json
#some code here
jsonStr = json.dumps(myListFromGooglePlaces)
#whatever you do to get it to php
and then as mentioned in my comment above
$arr = json_decode($json, true);
I hope that works for you.
Answer from Domenik Reitzner on Stack OverflowIn your python script do something like
import json
#some code here
jsonStr = json.dumps(myListFromGooglePlaces)
#whatever you do to get it to php
and then as mentioned in my comment above
$arr = json_decode($json, true);
I hope that works for you.
You could use json_decode function
j_obj = '[{ ....}]';
$array = json_decode($j_obj,true);
Just typecast it
$array = (array) $yourObject;
From Arrays:
If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side.
Example: Simple Object
$object = new StdClass;
$object->foo = 1;
$object->bar = 2;
var_dump( (array) $object );
Output:
array(2) {
'foo' => int(1)
'bar' => int(2)
}
Example: Complex Object
class Foo
{
private $foo;
protected $bar;
public $baz;
public function __construct()
{
$this->foo = 1;
$this->bar = 2;
$this->baz = new StdClass;
}
}
var_dump( (array) new Foo );
Output (with \0s edited in for clarity):
array(3) {
'\0Foo\0foo' => int(1)
'\0*\0bar' => int(2)
'baz' => class stdClass#2 (0) {}
}
Output with var_export instead of var_dump:
array (
'' . "\0" . 'Foo' . "\0" . 'foo' => 1,
'' . "\0" . '*' . "\0" . 'bar' => 2,
'baz' =>
stdClass::__set_state(array(
)),
)
To know more about php built-in class stdclass. You can read this documentation
Typecasting this way will not do deep casting of the object graph and you need to apply the null bytes (as explained in the manual quote) to access any non-public attributes. So this works best when casting StdClass objects or objects with only public properties. For quick and dirty (what you asked for) it's fine.
Also see this in-depth blog post:
- Fast PHP Object to Array conversion
You can quickly convert deeply nested objects to associative arrays by relying on the behavior of the JSON encode/decode functions:
$array = json_decode(json_encode($nested_object), true);
To understand: From PHP Array to Python? - Stack Overflow
How to convert an array to object in PHP? - Stack Overflow
Converting python dictionary into something php can use? Associative Array?
I would suggest using JSON, the whole point of it is to make communicating between computers/devices/software/languages easier...so, take the help :D
I dunno how to do it on Py end, but with PHP you would just use json_decode (second param is for result of json_decode to be assoc. array)
foreach (json_decode($output, true) as $item) { More on reddit.com PHP Recursively Convert Object to Array - Stack Overflow
How can I convert an array back into an object in PHP?
Can I use JSON encoding/decoding for all objects when learning how to convert object to array in PHP?
Why does get_object_vars() fail with non-public properties when learning how to convert object to array in PHP?
Update: A Completely different approach
There is a difficulty with the PHP script JSON-encoding a structure to produce a JSON string and then passing it as a command line argument since the string needs to be placed in double quotes because there can be embedded spaces in the encoded string. But the string itself can contain double quotes as start of string characters and within such a string. Confused? Who wouldn't be?
There is no problem however with writing such a string to a file and having the Python program read it in and decode it. But we don't want to have to deal with temporary files. So the solution is to pipe the data to the Python program where it can then be read in as stdin
Let's assume your array looks like:
$arr =
[
[
"FileName" => "\"\\ \nRon's20221227_202035.jpg",
"Model" => "27_202035.jpg",
"Longitude" => 106.90425,
"Latitude" => 106.90425
],
[
"FileName" => "20221227_202157.jpg",
"Model" => "SM-A528B",
"Longitude" => 106.9042428,
"Latitude" => -6.1676580997222
]
];
Note that I have modified your example slightly so that the first FileName field contains a " character, a ' character, an escape sequence \n representing the newline character and finally some spaces. Although your example does not contain these characters or some other escape sequence, I would like to be able to handle such a condition should it arise. This solution should work with such input.
PHP File
<?php
$arr =
[
[
"FileName" => "\"\\ \nRon's20221227_202035.jpg",
"Model" => "27_202035.jpg",
"Longitude" => 106.90425,
"Latitude" => 106.90425
],
[
"FileName" => "20221227_202157.jpg",
"Model" => "SM-A528B",
"Longitude" => 106.9042428,
"Latitude" => -6.1676580997222
]
];
// Encode string as JSON:
$json = json_encode($arr);
// Pipe the JSON string to the Python process's stdin and
// read the result from its stdout:
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w") // stdout is a pipe that the child will write to
);
$options = array('bypass_shell' => True); // Only has effect on Windows
//$process = proc_open("python3 test.py", $descriptorspec, $pipes, null, null, $options);
// For your actual environment:
$process = proc_open("D:/Anaconda/python.exe D:/xampp/htdocs/Klasifikasi_KNN/admin/test.py", $descriptorspec, $pipes, null, null, $options);
// Pipe the input for the Python program and close the pipe:
fwrite($pipes[0], $json);
fclose($pipes[0]);
// Read the result from the Python program and close its pipe
$result = stream_get_contents($pipes[1]);
fclose($pipes[1]);
# Now that we have closed the pipes, we can close the process:
$return_code = proc_close($process);
echo "Result from stdin:\n$result\n";
test.py
import json
import sys
DEBUG = True # for debugging purposes
if DEBUG:
import os
for k, v in sorted(os.environ.items()):
print(k, '->', v, file=sys.stderr)
else:
import numpy as np
import pandas as pd
# Load from stdin:
arr = json.load(sys.stdin)
# print each dictionary of the array:
for d in arr:
print(d)
Prints:
{'FileName': '"\\ \nRon\'s20221227_202035.jpg', 'Model': '27_202035.jpg', 'Longitude': 106.90425, 'Latitude': 106.90425}
{'FileName': '20221227_202157.jpg', 'Model': 'SM-A528B', 'Longitude': 106.9042428, 'Latitude': -6.1676580997222}
You just need to enclose in single quotes the argument to python:
shell_exec("python3 test.py '$json'");
Example
file.php
$data =
[
[
"FileName" => "20221227_202035.jpg",
"Model" => "27_202035.jpg",
"Longitude" => 106.90425,
"Latitude" => 106.90425
],
[
"FileName" => "20221227_202157.jpg",
"Model" => "SM-A528B",
"Longitude" => 106.9042428,
"Latitude" => -6.1676580997222
]
];
$json = json_encode($data);
// note: arg '$json' is single-quoted
echo shell_exec("python3 test.py '$json'");
test.py
import sys
import json
from pandas import json_normalize
data = sys.argv[1]
dict = json.loads(data)
df2 = json_normalize(dict)
print(df2)
Output
FileName Model Longitude Latitude
0 20221227_202035.jpg SM-A528B 106.904251 -6.167665
1 20221227_202157.jpg SM-A528B 106.904243 -6.167658
See: Escaping double qoutes when sending JSON as argument in python program
All of these are quite obvious really. I'm only listing the Pythonic ways to do these things. Update: Examples should now work in both Python 2 and Python 3. In Python 2 you could substitute xrange() for range() and iteritems() for items() for efficiency.
Example 1
PHP
$php = array(1,2,3,4,5,6,7,8,9,10);
for (
i < 10 ; $i ++)
echo
i]."<br>";
Python (generally you iterate over lists in Python, instead of accessing by index):
lst = [1,2,3,4,5,6,7,8,9,10]
for item in lst:
print(str(item) + "<br>")
Example 2
for (
i < 10 ; $i ++)
echo
i] = $i +1 ;
Python:
lst = range(1, 11)
for item in lst:
print(item)
Or maybe:
lst = []
for i in range(10):
lst.append(i + 1)
print(lst[-1]) # prints out last element
Example 3
$php = array(1,2,3,4,5,6,7,8,9,10);
foreach (
value)
echo $value."<br>";
Same as 1st
Example 4
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
Python:
lst = [1, 2, 3, 4]
lst = [val * 2 for val in lst]
Example 5
$arr = array("mot"=>"one", "hai"=>"two","ba"=> "three");
foreach (
key => $value) {
echo "Key: $key; Value: $value<br />\n";
}
Python (note that {...} creates a dict [dictionary] in Python, not a list/):
dct = {'mot': 'one', 'hai': 'two', 'ba': 'three'}
for key, value in dct.items():
print("Key: %s; Value: %s<br />" % (key, value))
Example 6
$arr = array("one", "two","three");
while (list(
value) = each($arr)) {
echo "Key: $key; Value: $value<br />\n";
}
Python:
lst = ['one', 'two', 'three']
for key, value in enumerate(lst):
print("Key: %d; Value: %s<br />" % (key, value))
Example 7
$arr = array("one", "two","three");
while ($element = each($arr)) {
echo "Key: $element['key']; Value: $element['value']<br />\n";
}
There is no direct Python equivalent to this.
Example 8
$products = array( array("ITL","INTEL","HARD"),
array("MIR", "MICROSOFT","SOFT"),
array("Py4C", "pythonkhmer.wordpress.com","TUTORIAL")
);
for (
row < 3; $row++)
{
for ($col = 0;
col++)
{
echo "|".$products[
col];
}
echo "<br>";
}
Python:
products = [['ITL', 'INTEL', 'HARD'],
['MIR', 'MICROSOFT', 'SOFT'],
['Py4C', 'pythonkhmer.wordpress.com', 'TUTORIAL']]
for product in products:
for item in product:
print('|' + item)
print('<br>')
Or maybe a more Pythonic version:
for product in products:
print('|%s<br>' % ('|'.join(product)))
"What is in Python?", quite a philosophical question, always a great way to start a day. I think what is in Python can best be answered by the Zen of Python (type import this in an interactive shell):
- Beautiful is better than ugly.
- Explicit is better than implicit.
- Simple is better than complex.
- Complex is better than complicated.
- Flat is better than nested.
- Sparse is better than dense.
- Readability counts.
- Special cases aren't special enough to break the rules.
- Although practicality beats purity.
- Errors should never pass silently.
- Unless explicitly silenced.
- In the face of ambiguity, refuse the temptation to guess.
- There should be one-- and preferably only one --obvious way to do it.
- Although that way may not be obvious at first unless you're Dutch.
- Now is better than never.
- Although never is often better than right now.
- If the implementation is hard to explain, it's a bad idea.
- If the implementation is easy to explain, it may be a good idea.
- Namespaces are one honking great idea -- let's do more of those!
Sorry, couldnt resist. To answer the question you meant to ask, I direct you to the Python documentation, specifically the section about looping techniques as linked to by lutz.
Unless the syntax in the documentation manage to completely confuse you (though I doubt it) you will see how a loop is defined in Python. And once you have understood that, you will understand, by definition, how they differ (syntactically) from the loops youre used to in PHP.
Still not satisfied? Hmm... I guess you should read the tutorial again. Then, come back and ask specific questions that could yield specific answers. You wont find any silver bullets for a question this broad.
In the simplest case, it's probably sufficient to "cast" the array as an object:
$object = (object) $array;
Another option would be to instantiate a standard class as a variable, and loop through your array while re-assigning the values:
$object = new stdClass();
foreach ($array as $key => $value)
{
$object->$key = $value;
}
As Edson Medina pointed out, a really clean solution is to use the built-in json_ functions:
$object = json_decode(json_encode($array), FALSE);
This also (recursively) converts all of your sub arrays into objects, which you may or may not want. Unfortunately it has a 2-3x performance hit over the looping approach.
Warning! (thanks to Ultra for the comment):
json_decode on different enviroments converts UTF-8 data in different ways. I end up getting on of values '240.00' locally and '240' on production - massive dissaster. Morover if conversion fails string get's returned as NULL
you can simply use type casting to convert an array to object.
// *convert array to object* Array([id]=> 321313[username]=>shahbaz)
$object = (object) $array_name;
//now it is converted to object and you can access it.
echo $object->username;
I'm more comfortable with python than php, but I've worked with it a bit (plus a lot of asp) so I am used to the style. However I'm having trouble passing output from python to php.
My py creates a dictionary object
{'key1': 123, 'key2': 456, 'key3': 789}My php then gets the output from that py file:
exec ('/usr/bin/python /var/www/html/data.py', $output);
foreach ($output as $item) {
print_r($item);
}This prints each dictionary entry to the page correctly. And each of these entries is what I need in a 'dictionary' type of object in php. I've seen references to an Associative Array, others saying to serialze with json.
Since I'm expecting to do more interactive work between python and php which way would be best? Is json the 'modern' way of doing it? Is it better form or more flexible to do this?
I'm looking for the right answer, not the quick copy and paste answer and I want to get better at this not just find a solution that fits today's need.
Thanks for any help that you can provide.
===========
edit: That was far easier than I expected. Here's what I'm doing now (basic usage example):
in the .py file, after getting all my results loaded into a dictionary object called 'results':
print json.dumps(results)
This is called in php like this (simple output function here, processing will come later):
$json = exec ('/usr/bin/python /var/www/html/data.py', $output);
$array = json_decode($json, true);
foreach($array as $item)
{
print($item['timestamp']);
}That gives me a page full of timestamps, just like I was hoping for. This was incredibly easy and knowing that it's compatible across languages is awesome.
Thanks for all the help and tips!
Here's my version. First it will test if the parameter passed is an array or object. If so it'll convert to array (if necessary) then run through each element (by reference) and recursively run the function on it. When it gets to a scalar value it will just return the value unmodified. Seems to work :-)
function object_to_array($obj) {
//only process if it's an object or array being passed to the function
if(is_object($obj) || is_array($obj)) {
$ret = (array) $obj;
foreach($ret as &$item) {
//recursively process EACH element regardless of type
$item = object_to_array($item);
}
return $ret;
}
//otherwise (i.e. for scalar values) return without modification
else {
return $obj;
}
}
You need to operate recursively.
This is the shortest I could come up with:
$toArray = function($x) use(&$toArray)
{
return (is_scalar($x) || is_null($x))
? $x
: array_map($toArray, (array) $x);
};
$array = $toArray($object);
AN EXAMPLE
<?php
$arr = array('test' => 1, 'ing' => 2, 'curveball' => array(1, 2, 3=>4) );
echo json_encode($arr);
?>
# elsewhere, in Python...
import simplejson
print simplejson.loads('{"test":1,"ing":2,"curveball":{"0":1,"1":2,"3":4}}')
Add to the PHP code a small snipet which JSON encodes the array, and displays / stores it on the disk.
echo json_encode($legendre_roots)
You can probably use that JSON code directly. if not, decode it in python and pprint it.