How to get "variable" of Response Object - php

I'm using an API in PHP that when I call one function it prints:
PagSeguro\Parsers\Transaction\CreditCard\Response Object
(
[date:PagSeguro\Parsers\Transaction\Response:private] => 2021-11-04T21:10:12.000-03:00
[code:PagSeguro\Parsers\Transaction\Response:private] => X
[reference:PagSeguro\Parsers\Transaction\Response:private] => Y
[...]
I need to get the code:PagSeguro\Parsers\Transaction\Response:private result but I didn't find out how. To call this response the line is: $result = $creditCard->register(\PagSeguro\Configuration\Configure::getAccountCredentials());

Here's the code that I did to make it work.
try {
//Get the crendentials and register the boleto payment
$result = $creditCard->register(
\PagSeguro\Configuration\Configure::getAccountCredentials()
);
$array = (array) $result; // makes it a "normal" array
$values = array_values($array); // get all those values
$transactionid = $values[1]; // returns the second value

Related

How to convert into json object like array

Mycode is given below:
// seatsToCancel=U23,L43,U12
$tin='S4243534'; //Booking id
$seatsToCancel=$_GET['seatsToCancel'];
$seatArray=explode(",",$seatsToCancel);
$seatCount=count($seatArray);
$SeatsTocancel=implode ( '", "', $seatArray );
$params = array(
"tin"=>"$tin",
"seatsToCancel"=>array($SeatsTocancel)
);
echo $params=json_encode($params);
I want output like this:
{"tin":"S4243534" ,"seatsToCancel":["U23","L43","U12"]}
I assume your $seatArray is ["U23","L43","U12"]?
In that case you can do like this:
$seatArray = ["U23","L43","U12"];
$finalarray = ["tin"=>$tin,"seatsToCancel" => $seatArray];
echo json_encode($finalarray); //{"tin":"S4243534","seatsToCancel":["U23","L43","U12"]}
Edited to add the new requirement from edited question
So I'm guessing that your seats to cancel are coming in as a comma-separated list from the URL. So all you need to do is explode() the GET parameter to turn it into an array, place it as the value to a key and json_encode() it.
i.e.
$seatsToCancel = explode(',', $_GET['seatsToCancel']);
$params = [
'tin' => $tin,
'seatsToCancel' => $seatsToCancel,
];
$paramsJson = json_encode($params);
That should get you the result you're after:
{"tin":"S4243534" ,"seatsToCancel":["U23","L43","U12"]}
You may want to consider what happens if the GET parameter is empty and whether or not you want any additional error checking.

Convert string to array in API call

I am passing an array as a string in parameter to an api in php like this:
http://xx.xx.xx.xx/api.php?query="array(done = 1)"
In my api file, I have used this array to hit a mongodb query:
$query = $_REQUEST['query'];
$cursor = $collection->find($query);
But this didn't work. When I hard-coded array(done = 1) into the find query, it seems to work fine.
if (array('done' => 1) == $query) {
echo "Y";
}
else {
echo "N";
}
The above code prints N. So I guess it's because $query is being passed as a string.
PS: I also tried json_encode, json_decode and unserialize but it didn't work. I might be doing omething wrong here.
Well make bit change in your query string, you passing in api request.
Suppose belowis your array.
$array = array('done' => 1, 'message' => 'success');
USE array_map_assoc function with some customization, which make easy to implode associative array
function array_map_assoc( $callback , $array ){
$r = array();
foreach ($array as $key=>$value)
$r[$key] = $callback($key,$value);
return $r;
}
Generate your data to be sent in api
our data
$queryString = implode('&',array_map_assoc(function($k,$v){return "$k=$v";},$array));
Now send your data with API
$url = "http://xx.xx.xx.xx/api.php?" . $queryString ;
Now use print_r($_GET) in your API page and you will receive data like below
Array
(
[done] => 1
[message] => success
)
This make your code easy to handle and use in either if condition or sql query.

Convert MySQL to Json ResultSet

I'm trying to turn my results into a json encoded string. I know that now working on an external api seems a bit much, but I do think that it's something that will come in handy as times goes on. Currently, I use the following function:
//API Details
public function APIReturnMembers() {
$query = <<<SQL
SELECT uname
FROM {$this->tprefix}accounts
SQL;
$encode = array();
$resource = $this->db->db->prepare( $query );
$resource->execute();
foreach($resource as $row) {
$encode[] = $row;
}
echo json_encode($encode);
}
It does what it's supposed to as far as returning results go, e.g.:
[{"uname" : "guildemporium"}, {"uname" : "doxramos"}]
When I saw that I was ecstatic! I was on my way to implementing my own API that others could use later on as I actually got somewhere! Now of course I have hit a hickup. Testing my API.
To run the code to get the results I used
$api_member_roster = "https://guildemporium.net/api.php?query=members";
$file_contents = #file_get_contents($api_member_roster); // omit warnings
$memberRoster = json_decode($file_contents, true);
print_r($memberRoster);
The good news!
It works. I get a result back, yay!
Now the Bad.
My Result is
[
0 => ['uname' => 'guildemporium'],
1 => ['uname' => 'doxramos']
]
So I've got this nice little number integer interrupting my return so that I can't use my original idea
foreach($memberRoster as $member) {
echo $member->uname;
}
Where did this extra number come from? Has it come in to ruin my life or am I messing up with my first time playing with the idea of returning results to another member? Find out next time on the X-Files. Or if you already know the answer that'd be great too!
The numbered rows in the array as the array indices of the result set. If you use print_r($encode);exit; right before you use echo json_encode($encode); in your script, you should see the exact same output.
When you create a PHP array, by default all indices are numbered indexes starting from zero and incrementing. You can have mixed array indices of numbers and letters, although is it better (mostly for your own sanity) if you stick to using only numbered indices or natural case English indices, where you would use an array like you would an object, eg.
$arr = [
'foo' => 'bar',
'bar' => 'foo'
];
print_r($arr);
/*Array
(
[foo] => bar
[bar] => foo
)*/
$arr = [
'foo','bar'
];
/*Array
(
[0] => foo
[1] => bar
)*/
Notice the difference in output? As for your last question; no. This is normal and expected behaviour. Consumers will iterate over the array, most likely using foreach in PHP, or for (x in y) in other languages.
What you're doing is:
$arr = [
['abc','123']
];
Which gives you:
Array
(
[0] => Array
(
[0] => abc
[1] => 123
)
)
In order to use $member->foo($bar); you need to unserialize the json objects.
In you api itself, you can return the response in json object
In your api.php
function Execute($data){
// Db Connectivity
// query
$result = mysqli_query($db, $query);
if( mysqli_num_rows($result) > 0 ){
$response = ProcessDbData($result);
}else{
$response = array();
}
mysqli_free_result($result);
return $response;
}
function ProcessDbData($obj){
$result = array();
if(!empty($obj)){
while($row = mysqli_fetch_assoc($obj)){
$result[] = $row;
}
return $result;
}
return $result;
}
function Convert2Json($obj){
if(is_array($obj)){
return json_encode($obj);
}
return $obj;
}
Calling api.php
$result = $this->ExecuteCurl('api.php?query=members');
print_r($result);
here you $result will contain the json object

How to parse JSON array of objects in PHP

I am new to php programming. Here in my project I am trying to parse JSON data coming from php web service. Here is the code in web service.
$query = "select * from tableA where ID = 1";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
$arr= array();
while ($row = mysql_fetch_assoc($result)) {
$arr['articles'][] = $row;
}
header('Content-type: application/json');
echo json_encode($arr);
}
else{
echo "No Names";
}
This is giving me data in this JSON format.
{"articles":[{"ID":"1","Title":"Welcome","Content":"This is the first article."}]}
Now here is my php page code.
<?php
$jfile = file_get_contents('http://localhost/api/get_content.php');
$final_res = json_decode($jfile, true) ;
var_dump( $final_res );
$content = $final_res->articles->Content;
?>
I want to show the content on webpage.
I know code at var_dump( $final_res ); is working. But after that code is wrong. I tried to look at many tutorials to find the solution but didn't find anyone. I don't know where I am wrong.
The second parameter of json_decode determines whether to return the result as an array instead of an object. Since you set it to true your result is an array and not an object.
$content = $final_res['articles'][0]['Content'];
As an alternative answer, if you want to use it as an object, use this code:
$a = '{"articles":[{"ID":"1","Title":"Welcome","Content":"This is the first article."}]}';
$final_res = json_decode($a);
echo '<pre>';
print_r($final_res);
echo '</pre><br>';
Note that I removed the second part (true) from the json_decode
Output:
stdClass Object
(
[articles] => Array
(
[0] => stdClass Object
(
[ID] => 1
[Title] => Welcome
[Content] => This is the first article.
)
)
)
Accessing Content:
echo 'Content: ' . $final_res->articles[0]->Content;
Output:
Content: This is the first article.
Run code

Accessing array value is null

Hello I have decoded a json string that I sent to my server and Im trying to get the values from him.
My problem is that I cant get the values from the inner arrays.
This is my code:
<?php
$post = file_get_contents('php://input');
$arrayBig = json_decode($post, true);
foreach ($arrayBig as $array)
{
$exercise = $array['exercise'];
$response["exercise"] = $exercise;
$response["array"] = $array;
echo json_encode($response);
}
?>
When I get the answer from my $response I get this values:
{"exercise":null,"array":[{"exercise":"foo","reps":"foo"}]}
Why is $array['exercise'] null if I can see that is not null in the array
Thanks.
From looking at the result of $response['array'], it looks like $array is actually this
[['exercise' => 'foo', 'reps' => 'foo']]
that is, an associative array nested within a numeric one. You should probably do some value checking before blindly assigning values but in the interest of brevity...
$exercise = $array[0]['exercise'];
Because of the [{...}] you are getting an array in an array when you decode your array key.
So:
$exercise = $array['exercise'];
Should be:
$exercise = $array[0]['exercise'];
See the example here.

Categories