Passing a Python list to php - php

I'm very new to php and I've been spending quite some type understanding how to pass arguments from Python to php and conversely.
I now know how to pass single variables, but I am still stuck and can't seem to find an answer to this one:
Php calls a Python script (that part works) that returns a list of strings. I'd like to process this list in php.
When I try:
print mylist
in myscript.py, and then :
$result = exec('python myscript.py')
it looks like php understands $result as a single string (which I agree makes sense).
I understand that maybe json can help or that I somehow need to use a dictionary instead of a list in python. However I can't figure out how exactly.
If anyone can help, it will be much appreciated! Thanks!

For instance:
myscript.py
import json
D = {'foo':1, 'baz': 2}
print json.dumps(D)
myscript.php
<?php
$result = json_decode(exec('python myscript.py'), true);
echo $result['foo'];

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.

Apparently your question was misleading. Was redirected here thinking this a solution for converting python lists to php array.
Posting a naive solution for ones wanting to convert lists to php array.
// 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"
)
)

$str = "[u'element1', u'element2', 'element3']";
$str = str_replace( array("u'", "[", "]"), array("'", ""), $str );
$strToPHPArray = str_getcsv($str, ",", "'");
print_r( $strToPHPArray );
Outputs
Array
(
[0] => element1
[1] => element2
[2] => element3
)

Related

PHP str_replace is not replacing value

I've been bashing my head against the wall for a couple of days on this, because all indications are that this SHOULD work, so I'm obviously missing something simple.
First I am using a function to grab an array of user submitted comments
function get_id_comment_info($id) {
global $connection;
$pdo = new PDO('mysql:host='.DB_SERVER.'; dbname='.DB_NAME, DB_USER, DB_PASS);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
$sql = "SELECT parks.parkid, parks.state, pcomment.parkid, pcomment.comment, pcomment.logname
FROM parks
LEFT JOIN pcomment
ON parks.parkid=pcomment.parkid
WHERE parks.id = '$id'";
$result = $pdo->query($sql);
$cominfo = $result->fetchAll();
return $cominfo;
}
Then, inside of a foreach loop which processes each park by id, I am working with the data:
foreach ($display_result as $parkrow) {
$id = $parkrow['parkid'];
$comments = get_id_comment_info($id);
$cleancom = str_replace("'", '', $comments);
print_r($cleancom);
.
.
.
}
The output for $cleancom is:
Array ( [0] => Array ( [parkid] => 462 [0] => 462 [state] => KS [1] =>
KS [2] => 462 [comment] => I have noticed some others here say don't
waste your time, but I think it's ok. Yes, it's smaller than most, but
there is fun to be had if you are an avid rider. [3] => I have noticed
some others here say don't waste your time, but I think it's ok. Yes,
it's smaller than most, but there is fun to be had if you are an avid
rider. [logname] => John32070 [4] => John32070 ) )
It does not remove the '. If I use preg_replace then the output is simply blank. I am missing something simple, but I just can't see it!
I have tested the str_replace() function and got the following results:
$myArray = array("h'i", array("hi'hi", "yo"));
print_r($myArray);
//RESULT: Array ( [0] => h'i [1] => Array ( [0] => hi'hi [1] => yo ) )
After applying the filter:
$filtered = str_replace( "'", "", $myArray);
print_r($filtered );
//RESULT: Array ( [0] => hi [1] => Array ( [0] => hi'hi [1] => yo ) )
What the previous results show is that any string values inside the top array are indeed being converted (h'i converted to hi) while any values that form part of the multidimensional array (any arrays within arrays) are not hi'hi remained the same. This seems to be how the function was created to work.
One solution is:
$cleancom = [];
foreach ($comments as $key => $value)
{
$cleancom[$key] = str_replace( "'", "", $value );
}
The reason the previous code works is because str_replace() is never being applied to a multidimensional array, while in your previous code it was. The previous code will not work however if you have something like an array within an array within another array, so if that ends up being the case in the future, I suggest you try finding a solution with callback functions.
Let me know if this worked for you.
Want to say something else, you should put the ids in an array, then use MySQL in() function, it only need to execute once, while your method will execute many times.

PHP from string to multiple arrays at the hand of placeholders

Good day,
I have an I think rather odd question and I also do not really know how to ask this question.
I want to create a string variable that looks like this:
[car]Ford[/car]
[car]Dodge[/car]
[car]Chevrolet[/car]
[car]Corvette[/car]
[motorcycle]Yamaha[/motorcycle]
[motorcycle]Ducati[/motorcycle]
[motorcycle]Gilera[/motorcycle]
[motorcycle]Kawasaki[/motorcycle]
This should be processed and look like:
$variable = array(
'car' => array(
'Ford',
'Dodge',
'Chevrolet',
'Corvette'
),
'motorcycle' => array(
'Yamaha',
'Ducati',
'Gilera',
'Kawasaki'
)
);
Does anyone know how to do this?
And what is it called what I am trying to do?
I want to explode the string into the two arrays. If it is a sub array
or two individual arrays. I do not care. I can always combine the
latter if I wish so.
But from the above mentioned string to two arrays. That is what I
want.
Solution by Dlporter98
<?php
///######## GET THE STRING FILE OR DIRECT INPUT
// $str = file_get_contents('file.txt');
$str = '[car]Ford[/car]
[car]Dodge[/car]
[car]Chevrolet[/car]
[car]Corvette[/car]
[motorcycle]Yamaha[/motorcycle]
[motorcycle]Ducati[/motorcycle]
[motorcycle]Gilera[/motorcycle]
[motorcycle]Kawasaki[/motorcycle]';
$str = explode(PHP_EOL, $str);
$finalArray = [];
foreach($str as $item){
//Use preg_match to capture the pieces of the string we want using a regular expression.
//The first capture will grab the text of the tag itself.
//The second capture will grab the text between the opening and closing tag.
//The resulting captures are placed into the matches array.
preg_match("/\[(.*?)\](.*?)\[/", $item, $matches);
//Build the final array structure.
$finalArray[$matches[1]][] = $matches[2];
}
print_r($finalArray);
?>
This gives me the following array:
Array
(
[car] => Array
(
[0] => Ford
[1] => Dodge
[2] => Chevrolet
[3] => Corvette
)
[motorcycle] => Array
(
[0] => Yamaha
[1] => Ducati
[2] => Gilera
[3] => Kawasaki
)
)
The small change I had to make was:
Change
$finalArray[$matches[1]] = $matches[2]
To:
$finalArray[$matches[1]][] = $matches[2];
Thanks a million!!
There are many ways to convert the information in this string to an associative array.
split the string on the new line into an array using the explode function:
$str = "[car]Ford[/car]
[car]Dodge[/car]
[car]Chevrolet[/car]
[car]Corvette[/car]
[motorcycle]Yamaha[/motorcycle]
[motorcycle]Ducati[/motorcycle]
[motorcycle]Gilera[/motorcycle]
[motorcycle]Kawasaki[/motorcycle]";
$items = explode(PHP_EOL, $str);
At this point each delimited item is now an array entry.
Array
(
[0] => [car]Ford[/car]
[1] => [car]Dodge[/car]
[2] => [car]Chevrolet[/car]
[3] => [car]Corvette[/car]
[4] => [motorcycle]Yamaha[/motorcycle]
[5] => [motorcycle]Ducati[/motorcycle]
[6] => [motorcycle]Gilera[/motorcycle]
[7] => [motorcycle]Kawasaki[/motorcycle]
)
Next, loop over the array and pull out the appropriate pieces needed to build the final associative array using the preg_match function with a regular expression:
$finalArray = [];
foreach($items as $item)
{
//Use preg_match to capture the pieces of the string we want using a regular expression.
//The first capture will grab the text of the tag itself.
//The second capture will grab the text between the opening and closing tag.
//The resulting captures are placed into the matches array.
preg_match("/\[(.*?)\](.*?)\[/", $item, $matches);
//Build the final array structure.
$finalArray[$matches[1]] = $matches[2]
}
The following is an example of what will be found in the matches array for a given iteration of the foreach loop.
Array
(
[0] => [motorcycle]Gilera[
[1] => motorcycle
[2] => Gilera
)
Please note that I use the PHP_EOL constant to explode the initial string. This may not work if the string was pulled from a different operating system than the one you are running this code on. You may need to replace this with the actual end of line characters that is being used by the string.
Why don't you create two separate arrays?
$cars = array("Ford", "Dodge", "Chevrolet", "Corvette");
$motorcycle = array("Yamaha", "Ducati", "Gilera", "Kawasaki");
You could also use an Associative array to do this.
$variable = array("Ford"=>"car", "Yamaha"=>"motorbike");

Get json object from it's position in the list

Let's say this is my json(I wont be able to change this json file):
{"success":true,
"users":{
"1036344647":{"name":"joel", "age":18},
"1036344365":{"name":"klant", "age":24},
"1036344352":{"name":"grabben", "age":23}
}
}
I also have a php code that collect this json data and decodes it.
$data = json_decode(file_get_contents("http://example.com/users/json"));
As you can see in my json each user has a random generated id that will change everytime i collect the data from my json file. Basicly i don't know any of the user ids.
But i still want to be able to print out a users name depending on it's position in the list.
For example: echo $data->users->[THE SECOND ID(the id with a user named "klant")]->name;
So i know this could be done easy if the json file was written as a array, but it is not.
Is there any way i can print out a object in the json depending on it's position in the list?
Try this:
function findUser($id)
{
$data = json_decode(file_get_contents("http://example.com/users/json"));
return isset($data[0]->users->$id) ? $data[0]->users->$id : null;
}
$user = findUser(1036344365);
var_dump($user);
It will output
object(stdClass)#4 (2) { ["name"]=> string(5) "klant" ["age"]=> int(24) }
You can build a 2nd array by "throwing away" those unique IDs with array_values() like so:
$array = json_decode($yourJSON, true);
$justValues = array_values( $array["users"] );
print_r( $justValues );
Output:
Array
(
[0] => Array
(
[name] => joel
[age] => 18
)
[1] => Array
(
[name] => klant
[age] => 24
)
[2] => Array
(
[name] => grabben
[age] => 23
)
)
You can then access each person's data like so:
echo $justValues[1]["name"]; // klant
No, it's not possible. JavaScript objects by design are unaware of "position" of their key-value pairs. Behind the scenes, that's what makes them powerful.
The first step is to rethink why you need to work with the JSON according to position.

How to change variable names inside array php

Ok so I have been struggling with this for hours now and I cannot seem to figure out what I'm trying to do. I have an array with many percent values placed inside and I'm printing out the first 5 of them. The $percent variables are acquired through similar_text
$array=array($percent12, $percent13, $percent14,
$percent15, $percent16, $percent17,
$percent18, $percent19, $percent110,
$percent111, $percent112, $percent113,
$percent114, $percent115, $percent116,
$percent117, $percent118, $percent119,
$percent120);
print_r(array_slice($array,0,5));
and it outputs like this:
Array ( [0] => 36.015505697169 [1] => 2.4181626187962 [2] => 2.4181626187962 [3] => 5.2153134902083 [4] => 100 )
So what i'm trying to figure out here is if it's possible to print the results of my array as they are listed above. example output would look like this:
Array ( [percent12] => 36.015505697169 [percent13] => 2.4181626187962 [percent14] => 2.4181626187962 [percent15] => 5.2153134902083 [percent16] => 100 )
i feel like this isn't possible, but if not, is there a way to assign the
[0]=> 36.015505697169 [1]=> 2.4181626187962
...etc to output something else say like:
[web0]=> 36.015505697169 [web1] => 2.4181626187962
Please help!! It's driving me crazy!!
You need to make it an associative array:
$array=array('percent12' => $percent12,
'percent13' => $percent13,
...);
I recommend using array_combine()
Basically you're just going to setup your new array with the keys, and pass in your current array for the values, thus creating a new array with the keys you want in the right place.
Try like
$myArr = array_slice($array,0,5);
$i = 0;
foreach($myArr as $key => $value) {
$newArr['web'.$i++] = $value;
}
print_r($newArr);

How to format my data in php

I have an array in php, with print_r it looks like this
Array (
[0] => Array ( [0] => 2 [1] => 3 [2] => 3 [3] => 1 [4] => 1 [5] => 4 [6] => 1 )
[1] => Array ( [0] => 1 [1] => 2 [2] => 2 [3] => 1 [4] => 1 [5] => 1 [6] => 1 )
)
when I do json_encode($mydata) it looks like this
[["2","3","3","1","1","4","1"],["1","2","2","1","1","1","1"]]
but I need this without the quotes, as the next processing simply needs a dataset like this:
var dataset = [ 5, 10, 15, 20, 25 ];
the dataset was never intended to use json standards, I simply need to get my array formatted correctly.
so the question is either "how do I remove quotes from json" which is simply nonstandard invalid json and won't get me the responses I'd need
OR
"how do I format this php array to be like the dataset".
it either involves a different kind of print function in php, or it involves some forloop regex in javascript
You need to use the JSON_NUMERIC_CHECK flag, this will force all numeric strings to be converted to numbers.
Like so:
json_encode($array,JSON_NUMERIC_CHECK);
Please note that this flag is only available from PHP version 5.3.3
Ehhh you could try this:
$d = array();
foreach($myData as $data) {
$d[] = "[" . implode(",", $data) . "]";
}
echo "[" . implode(",", $d) . "]";
Demo: http://codepad.org/nTveAGWm
Although echoing out json_encode($myData); worked as well: http://codepad.org/KTfQHz6s
The reason json_encode is putting quotes is because the data is a string.
Try this example to view the difference:
$arr = array(array(4,5,6), array(8,10, "11"));
print_r($arr);
echo "<br>";
echo json_encode($arr);
You can try to use intval to parse it as int before json_encoding
you could try this
$c = array(1,2,3);
echo "Non-associative array output: ", json_encode($c), "\n";
return this:
Non-associative array output: [1,2,3]
using your example string u can do smth like this
$arr = json_decode('[["2","3","3","1","1","4","1"],["1","2","2","1","1","1","1"]]');
foreach ($arr as &$val)
foreach ($val as &$item)
$item = (int)$item;
var_dump(json_encode($arr));
finally i get
string(33) "[[2,3,3,1,1,4,1],[1,2,2,1,1,1,1]]"

Categories