Couldnt use $_GET value - php

Before that, I searched around for problem same as me, but not found any..
I got a url http://mywebsite/rpc.php?stat=22
then, I have this code:
if(isset($_GET['stat'])){
$id = preg_replace("/[^0-9]/", "", $_GET['stat']);
$result = $rpc->get($id);
print_r($result);
}
this code will print array without result..
But, If I modify the code like this :
if(isset($_GET['stat'])){
//$id = preg_replace("/[^0-9]/", "", $_GET['stat']);
$result = $rpc->get(22);
print_r($result);
}
it will print the result as I want..
I tried echoing $_GET,and it output number 22..
is there anybody know what is the problem with my script?
this is the code that will process $rpc->get();
public function get ( $ids = array(), $fields = array() )
{
if ( !is_array( $ids ) ) $ids = array( $ids ); // Convert $ids to an array if only a single id was passed
if ( count( $fields ) == 0 ) $fields = array( "id", "name", "downloadDir", "rateDownload", "status", "doneDate", "haveValid", "totalSize" ); // Defaults
$request = array(
"fields" => $fields,
"ids" => $ids
);
return $this->request( "torrent-get", $request );
}

Your $rpc->get method seems to want an integer as the parameter, which you can get from the $_GET global like this:
$id = intval(preg_replace("/[^0-9]/", "", $_GET['stat']));

Related

preg match from json decoded page

I have one json decoded page and i want to scrap some data from that page.
I need to scrap this "value": "6fc975cd-bbd4-2daa-fc6b-1e8623f80caf|Antennas & Filter Products|Filter Products"
this is my json page
This is my function for preg match
public function getcategories( $page = '' ) {
$results = array();
preg_match_all( '~/\[value\]\s=>\s(.*?)\s*\[~', $page, $matchall );
debug($matchall);die;
if ( !empty( $matchall[1] ) ) {
foreach ( $matchall[1] as $single ) {
if ( strlen( $single ) > 1 ) {
$results[] = $single;
}
}
}
return $results;
}
And i call this function here
function checkpage( $page = '' ) {
$vars_all_array = $this->getvarsallfrompage( $page );
$get_api_url = $this->catspostreq($page);
$post_data = $this->makePostData( $vars_all_array, 0, 25 );
$jsonpage = $this->get_page( $get_api_url, array ('data' => $post_data, 'content-type'=> 'application/x-www-form-urlencoded; charset="UTF-8"; application/json' ) );
$json_decoded = json_decode($jsonpage);
$categories = $this->getcategories( $json_decoded );
debug($categories);die;
}
But something not working good, i have this error:
preg_match_all() expects parameter 2 to be string, array given
Can someone help me?
You don't need to do a preg_match_all to get the value out of $json_decoded, as json_decode() will return (if successfull) a perfectly readable array or object.
So to get the one specific value you can access it like so:
$value = $json_decoded['groupByResults'][0]->values[0]->value;
Since you want to have all the values in a new array, you could just iterate the values and pass it to a new array:
$categories = [];
foreach($json_decoded['groupByResults'][0]->values as $item) {
$categories[] = $item['value'];
}
There are built in array-functions that do that in one line and maybe quicker. This is to illustrate what you are doing with the data.
Using such a function array_column() would result in this one-liner:
$categories = array_column($json_decoded['groupByResults'][0]->values, "value");
Within your checkpagefunction you pass the value of json_decode to the getcategories function as parameter which return in most of case an array. and your getcategories you pass the $page parameter as a second parameter of preg_match_all
$json_decoded = json_decode($jsonpage);
$categories = $this->getcategories( $json_decoded );
and in your getcategories
preg_match_all('~/\[value\]\s=>\s(.*?)\s*\[~', $page, $matchall);
here $page is the result of json_decode which is an array. that why you are getting that error

Pushing two values from the database to one array

On line 6 I am pushing a value from the database to the array called $products. I would now like to give another value from the database ($row->image) to the same array which matches with $row->name.
Maybe it could make sense to use a two dimensional array but I don't know how to do this in this case.
$products = array();
foreach($_POST['selected_checkboxes'] as $value) {
if($result = $db->query("SELECT * FROM produkte WHERE $value = 1")){
while($row = $result->fetch_object()) {
if (!in_array($row->name, $products)) {
array_push($products, $row->name);
}
}
}
else {
array_push($products, 'error');
}
}
The result should show me the name and the image of both values which belong together.
You could do this, assuming you already have your $row->name and $row->image matching logic sorted:
if (!in_array($row->name, $products)) {
array_push( $products, array('name'=>$row->name, 'image'=>$row->image) );
}
You can try it like this:
$products = array();
foreach ( $_POST['selected_checkboxes'] as $value ) {
if ( $result = $db->query( "SELECT * FROM produkte WHERE $value = 1" ) ) {
while ( $row = $result->fetch_object() ) {
// if your name is unique you can do it like this,
// if not just take $row->id as index
if( isset( $products[$row->name] ) ) continue;
$products[$row->name] = array( "name" => $row->name, "image" => $row->image );
}
} else {
array_push( $products, 'error' );
}
}
// if you want to have plain digits as index you can get a reindexed array
$products = array_values( $products );
then you will get an array like that:
array(//$products
array(
"name" => "productname",
"image" => "productimage"
)
);
I think you can achieve that if you use a stdClass object.
$std = new stdClass();
$std->name = $row->name;
$std->image = $row->image;
array_push($products, $std);
Or you can change your sql query to
SELECT name, image FROM produkte WHERE $value = 1
and
array_push($products, $row);

PhP compare two arrays then write to file

I have inbound return data -> http://php.net/manual/en/function.json-decode.php that is in PhP array format. The file data is the same type. It is just $result from the previous cycle.
$result = api_query("mytrades", array("marketid" => $id));
How do I compare $result array with $file array and then over write FILE with $result data?
In other words, FILE and the data it contains is continuously being updated with $result
compare -> overwrite -> repeat at next execution.
I tried array_diff but it does not like my data types and I cannot find a work around.
Note: .db file is empty at first cycle but becomes populated at first write.
sample code with Array to string conversion error:
<?php
$id = 155;
require_once('phpPlay.php');
$result = api_query("mytrades", array("marketid" => $id));
$lines = file("myDB.db");
$arrayDiffresult = array_diff ( $result, $lines);
var_dump($result);
file_put_contents('myDB.db', print_r($result, true));
?>
var_dump($result);
I think, you looking for some serialization, json_encoding for example.
$result = array(
'return' => array(
array(
"tradeid" =>"74038377",
"tradetype" =>"Sell",
"datetime" =>"2014-11-12 16:05:32",
"tradeprice" =>"0.00675000",
"quantity" =>"22.18670000",
"fee" =>"-0.00007488",
"total" =>"0.14976023",
"initiate_ordertype" =>"Buy",
"order_id" =>"197009493",
),
array(
"tradeid" =>"2",
"tradetype" =>"Sell",
"datetime" =>"2014-11-12 16:05:32",
"tradeprice" =>"0.00675000",
"quantity" =>"22.18670000",
"fee" =>"-0.00007488",
"total" =>"0.14976023",
"initiate_ordertype" =>"Buy",
"order_id" =>"2",
)
)
);
function getdiff($new, $old)
{
//implement right logical diff here
$diff = array();
$old_serialized = array();
foreach ($old as $item) {
$old_serialized[] = json_encode($item);
}
foreach ($new as $item) {
if (in_array(json_encode($item), $old_serialized)) {
continue;
}
$diff[] = $item;
}
return $diff;
}
$old = file_exists('1.db') ? json_decode(file_get_contents('1.db'), 1) : array();
$arrayDiffresult = getdiff($result['return'], $old);
file_put_contents('1.db', json_encode($result['return']));
print_r($arrayDiffresult);

JSONPath Query to get Node-names?

Consider the following piece of JSONPath:
{
"result":[
{
"type":"Residence",
"street":"Piazza di Spagna",
"city":"-4:0"
},
{
"type":"Residence",
"street":"test",
"city":"-4:1"
}
]
}
Is it possible to get a list of all the node-names?
So for example, I want a list like: type, street, city.
Try this
$arr = (json_decode($json)->result[0]);
$array = get_object_vars($arr);
$properties = array_keys($array);
print_r($properties);`
Out put will be
Array
(
[0] => type
[1] => street
[2] => city
)
On PHP >= 5.4 you can obtain your keys with one line of code:
$nodeNames = array_keys( json_decode( $jsonString, True )['result'][0] );
3v4l.org demo
On lower versions (PHP >= 5.2.16), you have to break above code in two lines:
$array = json_decode( $jsonString, True );
$nodeNames = array_keys( $array['result'][0] );
I decode the JSON string with second parameter as True to force result as array, then I call array_keys to obtain the keys of array['result'][0].
Edit: more flexibility
Your example can be processed as above without problems, but what happens if original JSON string has different keys? The above solution will fail if in the first result row there are not all the keys. To obtain all the keys, you can use this code:
$array = json_decode( $jsonString, True );
$nodeNames = array();
foreach( $array['result'] as $row )
{
$nodeNames = array_unique( array_merge( $nodeNames, array_keys( $row ) ) );
}
or, using array_filter, with this code:
$array = json_decode( $jsonString, True );
$nodeNames = array();
array_filter
(
$array['result'],
function( $row )
{
global $nodeNames;
$nodeNames = array_unique( array_merge( $nodeNames, array_keys( $row ) ) );
}
);
By this two equivalent examples, I process each result row, merging the keys in $nodeNames array and using array_unique to delete duplicate keys.
Read more about array_keys()
Read more about array_unique()
Read more about array_filter()
You can use following function to print all keys in an array format
print_r(array_keys($array));
Is the JSON Path definitely going to follow that structure every time? As in Result => Arrays all of which have the same Nodes.
If it does then the following will work:
function getJsonNodes($json) {
$nodes = array();
$decoded = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \InvalidArgumentException('Invalid JSON String passed to getJsonNodes()');
}
$result = $decoded['result'];
if (is_array($result)) {
$nodes = array_keys($result[0]);
}
return $nodes;
}
Usage would be something like:
try {
$nodes = getJsonNodes($json);
} catch (\InvalidArgumentException $e) {
echo $e->getMessage();
}
Means you can catch any Invalid JSON strings that could potentially be passed and mess with the output.
Although as I stated, the above solution will only work if your JSON Path follows the structure to put in your OP.
You can see it in use here: https://ideone.com/dlvdu2
Hope it helps either way.
Is it possible to get a list of all the node-names?
$object = json_decode($json);
$json_array = $object->result;
foreach ($json_array as $key => $value) {
$object_var = get_object_vars($value);
$object_key = array_keys($object_var);
var_dump($object_key);//will get all node_names!
}
Try this
$result[0].type , $result[0].street, $result[0].city
Please check the below code ..Hope will work
<?php
$text[]=array(
result=>array(
"type"=>"Residence",
"street"=>"pizza",
"city"=>"ini"
),
array(
"type"=>"Residence",
"street"=>"pizza",
"city"=>"ini"
)
);
echo json_encode($text);
?>

How to listSubscribe in Groups Mailchimp API 1.3

As the example below shows how to call on the fields, my question is how to call a multiple checked checkbox. please give me an example
$merge_vars = array('FNAME'=>'Test', 'LNAME'=>'Account',
'GROUPINGS'=>array(
array('name'=>'Your Interests:', 'groups'=>'Bananas,Apples'),
array('id'=>22, 'groups'=>'Trains'),
)
);
I get a solution for this.
To get the multiple checked checkbox you need to do a looping and set it in array then change the array to a string.
if(!empty($_POST['listbox']))
{
foreach($_POST['listbox'] as $value => $val)
{
$values[] = $val;
}
$groups = implode(",", $values);
}
then set it in the merge_vars
$merge_vars = array('FNAME'=>'Test', 'LNAME'=>'Account',
'GROUPINGS'=>array(
array('name'=>'Your Interests:', 'groups'=> $groups)
)
);
Hope it helps :)
You must put the separated by commas but you must ensure that they have commas escaped:
$groups = array();
if(!empty($_POST['listbox'])) {
$interests = array();
foreach($_POST['listbox'] as $interest)
{
$interests[] = str_replace(',', '\,', $interest);
}
$groups = implode(",", $interests);
}
$merge_vars = array(
'FNAME'=>'Test',
'LNAME'=>'Account',
'GROUPINGS'=> array(
array(
'name'=>'Your Interests:',
'groups'=> $groups
),
array(
'id'=>22,
'groups'=>'Trains'
)
)
);
If you are sure that the interest string do not have commas you can just do this:
$groups = implode(',', $_POST['listbox']);

Categories