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
I have an array with values that are objects wrapped as strings, how can I turn them back into objects without calling them? ['randomNumber' => '$this->faker->randomNumber()']
This array is being passed into a stub (writing a php file):
$replace = [
'{{mappedResult}}' => var_export($mappedResults, 1),
];
instead of getting this array:
$mappedResults = ['randomNumber' => $this->faker->randomNumber()]
I get this array instead:
$mappedResults = ['randomNumber' => '$this->faker->randomNumber()']
If you want to use the return value of the method call as the value in the map, you can use eval:
foreach ($mappedResults as $key => $value)
$mappedResults[$key] = eval($value)
Note eval returns NULL unless a return statement is called in the code string. Then the value passed to return is returned. If there is a parse error in the code string, eval() returns FALSE.
Hence you don't want to call and evaluate the code and based on my understanding you want to recreate the php file, you should use a custom export function that can remove quotations:
function export($input) {
$response = [];
foreach($input as $key => $value)
$response[] = var_export($key, true) . " => " . $value;
return "[".implode(",",$response)."]";
}
I have this array:
$users = array();
// Finally, loop over the results
foreach( $select as $email => $ip )
{
$users[$email] = $ip;
}
Now i want to pass this array to ajax and print in another script:
$html="<center>Check users for spam</center>";
mcheck.php
echo $_POST['users'];
This code does not work. How can i do this?
As Sergiu Costas pointer out, the best way is to JSON encode it and then decode, but you can also try:
$html="<center>Check users for spam</center>";
If your $users array is:
$users = array( array('email' => 'a#email.com'), array('email' => 'b#email.com')));
then http_build_query('users' => $users) will generate:
users%5B0%5D%5Bemail%5D=a%40email.com&users%5B1%5D%5Bemail%5D=b%40email.com
which is the url-encoded version of:
users[0][email]=a#email.com&users[1][email]=b#email.com
which will be decoded back to array in mcheck.php
The Best way is to encode array into JSON format.
In PHP:
$users_json = json_encode($users);
// To decode in javascript
var obj = JSON.parse(json_str);
if u want to pass php array to js you can json_encode the array to do that.
$html="<center>Check users for spam</center>";
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
I'm trying to build URL query from an Array that looks like that:
$serials = ['3804689','3801239','3555689','3804687','1404689','6804689','8844689','4104689','2704689','4604689'];
I would like to get query like that:
localhost/get?serial=3804689&serial=3801239&serial=3555689
(you get the idea)
I'm trying to use http_build_query($serials, 'serial', '&'); but it adds the numeric index to the prefix 'serial'.
Any idea how to remove that numeric index?
Well you can't really have the same GET parameter in the string, After all if you try to access that variable server side, what would you use?
$_GET['serial'] - But which serial would it get?
If you really want to get a list of serials, Simply turn the array into a string, save it as an array and there you go. for example :
$serials = "string of serials, delimited by &";
Then you can use the http build query.
Maybe use a foreach:
$get = "localhost/get?serial=" . $serials[0];
unset( $serials[0] );
foreach( $serials AS serial ){
$get .= "&serial=$serial;
}
Just as an FYI, PHP doesn't handle multiple GET variables with the same name natively. You will have to implement something fairly custom. If you are wanting to create a query string with multiple serial numbers, use a delimiter like _ or -.
Ex: soemthing.com/serials.php?serials=09830-20990-91234-12342
To do something like this from an array would be simple
$get_uri = "?serial=" . implode("-", $serials);
You would be able to get the array back from a the string using an explode to
$serials = explode("-", $_GET['serials']);
Yes its quite possible to have such format, you have to build it query string by indices. Like this:
No need to build the query string by hand, use http_build_query() in this case:
$serials = ['3804689','3801239','3555689','3804687','1404689','6804689','8844689','4104689','2704689','4604689'];
$temp = $serials;
unset($serials);
$serials['serial'] = $temp;
$query_string = http_build_query($serials);
echo urldecode($query_string);
// serial[0]=3804689&serial[1]=3801239&serial[2]=3555689&serial[3]=3804687&serial[4]=1404689&serial[5]=6804689&serial[6]=8844689&serial[7]=4104689&serial[8]=2704689&serial[9]=4604689
And then finally, if you need to process it somewhere, just access it thru $_GET['serial'];
$serials = $_GET['serial']; // this will now hold an array of serials
You can also try this
$get = "localhost/get?serial=";
$serials = ['3804689','3801239','3555689','3804687','1404689','6804689','8844689','4104689','2704689','4604689'];
$list = implode("&serial=",$serials);
echo $get.$list;
Having the same GET parameter will not work this way. You will need to use an array in the get parameter:
localhost/get?serial[]=3804689&serial[]=3801239&serial[]=3555689
IF you just print $_GET through this URL, you will receive
Array ( [serial] => Array ( [0] => 380468 [1] => 3801239 [2]=> 3555689) )
Then you can do this to build your query string
$query_str = 'serial[]='.implode('&serials[]=',$serials);
You can try this version.
$serials = ['3804689','3801239','3555689','3804687','1404689','6804689','8844689','4104689','2704689','4604689'];
$get = implode('&serials[]=',$serials);
echo 'test';
var_dump($_GET['serials']);
Result