Converting complexObjectArray to a Usable Array - php

I have a script which has output which looks like the following:
Which is something I've not experienced before. Normally the result would be the array and then the stdClass Object which I convert to an array using (array) $result. This one seems to be nested an extra 2 times however, so I have no idea how to access it so that I can turn each of those objects into an array.
So what I need to be able to achieve, for example, is that if I use the code echo $orders[0]->customer_id, the result would be 716'.
Could anybody please advise? My code is below if required. Thank you very much.
<?php
$client= new SoapClient('*Magento URL*');
$session_id = $client->login((object)array('username' => '*Magento Username*', 'apiKey' => '*Magento Password*'));
try {
$result = $client->salesOrderList((object)array('sessionId' => $session_id->result, 'filters' => null));
$orders = (array) $result;
echo '<pre>', print_r($orders), '</pre>';
} catch (SoapFault $e) {
echo 'Error: ', $e->getMessage(), '<hr>';
}
?>

$result is an object with a result property which is an object with a complexObjectArray property that is an integer indexed array of objects. So:
$orders = $result->result->complexObjectArray;
Then:
echo $orders[0]->customer_id;
If there is more than one item in the array then you would need to loop over it. If there is only ever one then include the 0 when defining $orders:
$orders = $result->result->complexObjectArray[0];
Then:
echo $orders->customer_id;

Related

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

Multi dimension array

I am really struggling with arrays in general but I can't seem to do anything with this: https://www.easycron.com/document/list
I want to be able to access each "field". For example the [cron_job_name] for [2]. So in that example the result I'd be looking for is "Send newsletters".
I have been messing around all night long but I think the thing I am not getting past is that it has the [status] => success [cron_jobs] => Array at the top.
So far the code I have is this:
$json = file_get_contents("https://www.easycron.com/rest/list?token=[MY KEY]&sortby=cronId&order=desc");
$myArray = json_decode($json,true);
echo "<pre>";
print_r($myArray);
echo "</pre>";
All this really does though is gets me a copy of what is on that page.
if you are able to print_r the array response, then you can cycle
if($myArray['status'] ==='success') {
$crons = $myArray['cron_jobs'];
foreach($crons as $cron){
if($cron['cron_job_name'] == 'Send newsletters') {
// Do your proccessing
break;
}
}
}

Php json decode with child

I been looking thru the posts here all day but can't figure out what I'm doing wrong. (I'm new to php and json)
Here is my code that work.
$json = '{"id":1234,"img":"1.jpg"}';
$data = json_decode($json, true);
echo $data["img"];
But when the json respond is this
$json = '{"demo1":[{"id":1234,"img":"1.jpg"}],"userId":1}';
it's a big harder for me. then img is a child of demo1? How to get it?
Thx. :)
Figuring out the array indices
As you're new to PHP, I'll explain how to figure out the array indces of the required array value. In PHP, there are many functions for debugging — print_r() and var_dump() are two of them. print_r() gives us a human-readable output of the supplied array, and var_dump() gives us a structured output along with the variable types and values.
In this case, print_r() should suffice:
$json = '{"demo1":[{"id":1234,"img":"1.jpg"}],"userId":1}';
$data = json_decode($json, true);
// wrap the output in <pre> tags to get a prettier output
echo '<pre>';
print_r($data);
echo '</pre>';
This will produce the following output:
Array
(
[demo1] => Array
(
[0] => Array
(
[id] => 1234
[img] => 1.jpg
)
)
[userId] => 1
)
From there, it should be pretty easy for you to figure out how to access the required vaule.
$data['demo1'][0]['img'];
Creating a helper function for ease of use
For ease of use, you can create a helper function to make this process easier. Whenever you want to view the contents of an array, you can simply call dump_array($array); and be done with it. No more messing around with <pre> tags or print_r().
Function code:
function dump_array($array) {
echo '<pre>' . print_r($array, TRUE) . '</pre>';
}
Usage example:
$arr = ['foo' => range('a','i'), 'bar' => range(1,9)];
dump_array($arr);
after decoding :
echo $data->demo[0]->img;
Basically, a { in JSON leads to a -> (it's an object).
And a [ to a [], it's an array.

Cannot use string offset as an array in

I have an array $aMethods whose print_r output is this:
Array
(
[0] => Array
(
[pattern] =>
[return_media] => 1
[return_name] =>
)
)
I'm trying to access 'return_media' with this code:
$iReturnMedia = $aMethods[0]->return_media;
echo $iReturnMedia;
Also, when I tried this:
$iReturnMedia = $aMethods[0]['return_media'];
I get an error stating: Cannot use string offset as an array in...
But it's not working, $iReturnMedia comes back as blank. Could someone tell me what I'm doing wrong here?
EDIT: $aMethods is set in a foreach loop as such:
foreach ($aMethodList as $sMethodGroup => $aMethods) { //insert code from above }
You need to use:
$iReturnMedia = $aMethods[0]['return_media'];
The operation -> is for accessing object properties. Since you're just dealing with nested arrays, you need to index them with [].
Access the array value by key.
$iReturnMedia = $aMethods[0]['return_media'];
echo $iReturnMedia;
Your accessing it as if it was an object in an array, you do it like:
$iReturnMedia = $aMethods[0]['return_media'];
echo $iReturnMedia;
Try this,
$iReturnMedia = $aMethodList[$sMethodGroup][0]['return_media'];
echo $iReturnMedia;
Try to var_dump($aMethods) . It will be give exactly idea of that array...
find below the code to access the array values -
foreach ($aMethodList as $sMethodGroup => $aMethods) {
echo $aMethods[0]['return_media'];
}

Categories