PHP Arrays and how to get an array from an object - php

hoping someone here might be able to advise on what the syntax should be to get the data in the transactions array within the data object below
{
"data": {
"pages":10,
"current":1,
"token":"1234-1234-1234-1234",
"transactions":[{"id"}]
}
}
im trying to output the data
<?php foreach ($someArray as $key => $value){
echo "<tr><td>". $value[columns][tranid];
echo "</td><td>". $value[recordtype];
echo "</td><td>". $value[columns][trandate];
echo "</td><td>". $value[columns][poref];
echo "</td><td>". $value[columns][ref][name];
echo "</td><td>$". number_format($value[columns][amount], 0.00, '.', ',');
echo "</td><td><a class='woocommerce-button button' href='https://test.com/?a=print&token=". $pmToken ."&i=". base64_encode("PM-" + $value[columns][internalid][internalid]) ."' target='_new'>Print</a>";
echo "</td></tr>";
}
?>
Im so new to PHP Im not sure how to grab the data
I assume in alot of other languages its just a case of
$someArray.transactions would be the way to do it, but I cant figure out how to get it in PHP

If you want to convert object into array, so you should use php function
$object = json_decode(json_encode($array), FALSE);

Lets say your object is:
$obj = '{
"data":
{
"pages":10,
"current":1,
"token":"1234-1234-1234-1234",
"transactions":[{"id"}]
}
}';
$arr = (array)$obj;
var_dump($arr); //This will be displayed as array
Working example:
http://codepad.org/uCIB7kfh

Use json_decode()
In your case, put
$s = '{"key":"value"}'
$someArray = json_decode($s);
before the for loop, you can then add
var_dump($someArray);
to view the structure and fetch the corresponding data value.

Related

Loop through each element under "Data"

I'm using Kucoin's API to get a list of coins.
Here is the endpoint: https://api.kucoin.com/v1/market/open/coins
And here's my code:
$kucoin_coins = file_get_contents('https://api.kucoin.com/v1/market/open/coins');
$kucoin_coins = json_decode($kucoin_coins, true);
print_r($kucoin_coins);
I can see how to target one coin like so:
echo "name: " . $kucoin_coins['data'][0]['name'];
But I can't see how to loop through them.
How can I loop through each of the "coins" returned here? They are under the "data" part that is returned. I'm sorry, I'm just not seeing how to do it right now. Thank you!
You can loop through the decoded elements using the foreach command:
foreach ($kucoin_coins['data'] as $coin) {
//do your magic here.
}
But I usually prefer using json_decode($kucoin_coins) rather than the one for arrays. I believe this:
$item->attribute;
Is easier to write than this one:
$item['attribute'];
foreach($kucoin_coins['data'] as $data) {
echo $data['name']."\n";
}
You can loop through your data using foreach() like this
<?php
$kucoin_coins = file_get_contents('https://api.kucoin.com/v1/market/open/coins');
$kucoin_coins = json_decode($kucoin_coins, true);
print '<pre>';
print_r($kucoin_coins);
print '</pre>';
foreach($kucoin_coins['data'] as $key=>$value){
echo $value['name']. "<br/>";
}
?>
See DEMO: http://phpfiddle.org/main/code/q6kt-dctg

Parsing JSON in for each with increment PHP

I'm trying to parse a json file into a for each loop. The issue is the data is nested in containers with incremented numbers, which is an issue as I can't then just grab each value in the foreach. I've spent a while trying to find a way to get this to work and I've come up empty. Any idea?
Here is the json file tidied up so you can see what I mean - http://www.jsoneditoronline.org/?url=http://ergast.com/api/f1/current/last/results.json
I am trying to get values such as [number] but I also want to get deeper values such as [Driver][code]
<?php
// get ergast json feed for next race
$url = "http://ergast.com/api/f1/current/last/results.json";
// store array in $nextRace
$json = file_get_contents($url);
$nextRace = json_decode($json, TRUE);
$a = 0;
// get array for next race
// get date and figure out how many days remaining
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'][' . $a++ . '];
foreach ($nextRaceDate['data'] as $key=>$val) {
echo $val['number'];
}
?>
While decoding the json there's no need to flatten the object to an Associative array. Just use it how it is supposed to be used.
$nextRace = json_decode($json);
$nextRaceDate = $nextRace->MRData->RaceTable->Races[0]->Results;
foreach($nextRaceDate as $race){
echo 'Race number : ' . $race->number . '<br>';
echo 'Race Points : ' . $race->points. '<br>';
echo '====================' . '<br>';
}
CodePad Example
You are nearly correct with your code, you are doing it wrong when you try the $a++. Remove the $a = 0, you won't need it.
Till here you are correct
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results']
What you have to do next is this
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'];
foreach($nextRaceDate as $key => $value){
foreach($value as $key2 => $value2)
print_r($value2);
So, in my code, you are stopping at Results, and then, you want to iterate over all the results, from 0 to X, the first foreach will do that, you have to access $value for that. So, add another foreach to iterate over all the content that $value has.
There you go, I added a print_r to show you that you are iterating over what you wanted.
The problem is how you access to the elements in the nested array.
Here a way to do it:
$mrData = json_decode($json, true)['MRData'];
foreach($nextRace['RaceTable']['Races'] as $race) {
// Here you have access to race's informations
echo $race['raceName'];
echo $race['round'];
// ...
foreach($race['Results'] as $result) {
// And here to a result
echo $result['number'];
echo $result['position'];
// ...
}
}
I don't know where come's from your object, but, if you're sure that you'll get everytime one race, the first loop could be suppressed and use the shortcut:
$race = json_decode($json, true)['MRData']['RaceTable']['Races'][0];
Your problem is that the index must be an integer because the array is non associative. Giving a string, php was looking for the key '$a++', and not the index with the value in $a.
If you need only the number of the first race, try this way
$a = 0;
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'][$a];
echo "\n".$nextRaceDate['number'];
maybe you need to iterate in the 'Races' attribute
If you need all, try this way :
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races'];
foreach ($nextRaceDate as $key => $val) {
foreach ($val['Results'] as $val2) {
echo "\nNUMBER " . $val2['number'];
}
}

Json To PHP issues outputting an array

Im currently playing around with some php and JSON, i know abit of PHP pretty much nothing of JSON but ive managed to get about halfway where i need to be currently i have this section of code.
<?php
$json = file_get_contents('http://eu.battle.net/api/wow/character/Ragnaros/Smoosher?fields=progression');
$data = json_decode($json, true);
foreach ($data['progression']['raids'] as $raid) {
echo "Raid: ", $raid['name'];
echo " Normal: ", $raid['normal'];
echo " Heroic: ", $raid['heroic'];
echo " id: ", $raid['id'];
echo " Boss's: ", $raid['bosses']['name'];
?>
<p>
<?php
};
foreach ($data['progression']['raids']['bosses'] as $boss) {
echo " Boss Name: ", $boss['name'];
}
print_r($boss);
#echo $data->name;
?>
Now the first foreach works fine, no issues what that it pulls the data out into the page fine, however i noticed that seemed to be another (Array?) within the one i was out putting so first i tried
echo " Boss's: ", $raid['bosses']['name'];
Which outputs nothing but the word boss's, and nothing from within the array, so i thought maybe i need another foreach statement and start pulling that through. However this part
foreach ($data['progression']['raids']['bosses'] as $boss) {
echo " Boss Name: ", $boss['name'];
}
Gives an error
Warning: Invalid argument supplied for foreach() in xxxxxx/xx/xxxxx/wow/test.php on line 22
And i cant see what im doing wrong :( any help would be great, the json im pulling from is
http://eu.battle.net/api/wow/character/Ragnaros/Smoosher?fields=progression
Your problem here is that $data['progression']['raids']['bosses'] is not an array.
$data['progression']['raids'] is an array of arrays, and each of those arrays has a bosses key, so your data looks like this:
$data['progression']['raids'][0]['bosses'] - note the [0] in there, as opposed to just $data['progression']['raids']['bosses']
You should nest the loop on bosses within the previous loop, e.g.
<?php
$json = file_get_contents('http://eu.battle.net/api/wow/character/Ragnaros/Smoosher?fields=progression');
$data = json_decode($json, true);
foreach ($data['progression']['raids'] as $raid)
{
echo "Raid: ", $raid['name'];
echo " Normal: ", $raid['normal'];
echo " Heroic: ", $raid['heroic'];
echo " id: ", $raid['id'];
foreach ($raid['bosses'] as $boss)
{
echo " Boss Name: ", $boss['name'];
}
?>
<p>
<?php
};
$data['progression']['raids']
This variable is an array.
You can use foreach at this array.
foreach($data['progression']['raids'] as $raid) {
forach($raid['bosses'] as $boss) {
//here is your boss
}
}
you should write like this for second foreach :-
$data['progression']['raids'] hold array in it and ['bosses'] has an array element as member for $data['progression']['raids'].
foreach ($data['progression']['raids'] as $boss)
foreach($boss['bosses'] as $boss1)
{
echo " Boss Name: ", $boss1['name'];
echo '<br>';
}

convert mysql resultset into a (name, data) object to be fed into HighCharts

I am using HighCharts Bar graph to plot data from mysql resultset into a bar graph.
Now the resultset of my query is as below:
Name Expense
-----------------
July 700.0000
August 450.0000
September 1700.0000
The series property of HighCharts require data in below format to plot the graph
[
{name:"July",data:[700.0000]},
{name:"August",data:[450.0000]},
{name:"September",data:[1700.0000]}
]
So I thought of coverting my resultset into a JSON object using json_encode($row).
But I got the following output:
[{"name":"July","data":"700.0000"},
{"name":"August","data":"450.0000"},
{"name":"September","data":"1700.0000"}]
Doubts:
Is there a way to get/convert the resultset in exactly the same format as is required by the series property of HighCharts?
Also can I use an object of created in the php block, directly into the javascript? Say I create an object $jsonNameData out of my resultset. Then can I use it in the javascript as
series: <? echo $jsonNameData ?>
EDIT:
I was able to solve Q1 by doing the following:
$count = 0;
$strSeries = "[";
while($r = mysql_fetch_assoc($result)) {
if($count == 0){
$strSeries .= "{name:'" . $r['name'] . "',";
$strSeries .= "data:[" . $r['data'] . ']}';
$count = 1;
}
else {
$strSeries .= ",{name:'" . $r['name'] . "',";
$strSeries .= "data:[" . $r['data'] . ']}';
}
$rows[] = $r;
}
$strSeries .= "]";
Got the required string into $strSeries.
Now the problem is the second question. I assigned the value of $strSeries to a variable in javascript but when I use that variable as
series: variableName
It is not plotting the graph properly even though the variable has proper value (checked through alert).
Not got a chance to run the code below, but this should work or something very similar to this
$series=array();
while($item = mysql_fetch_assoc($result)) {
$serie=array(
"name" => $item['name'],
"data" => array(floatval($item['data']))
);
array_push($series,$serie);
}
echo json_encode($series);
An advice is to always stick to json_encode() for doing the jsonification. You may want to go through this example on the reference page to learn about how json_encode works with arrays in particular
EDIT: To answer your 2nd question. You may be getting a highchart error #14 in the javascript console? Have a look at this question Highcharts returning error 14
P.S. Please don't mix multiple questions in one, post them separately, also use tools like javascript console and SO search more effectively
I would try this :
$jsonObj = '[';
foreach($mysqlResul as $item){
$jsonObj .= '{"name":"'.$item['name'].'","data":['.$item['data'].']},';
}
// strip off last comma
$jsonObj = substr(0,strlen($jsonObj)-1,$jsonObj);
$jsonObj .= ']';
select concat('{name:"', name, '",data:[', expense, ']}') as foo
from bar

How to parse a web service returned response into an array in PHP

I am updating my question with a few breakthroughs i was able to achieve today. I used get_object_vars.
This code was able to print out the value i am trying to iterate over.
$fileStatus = $ServicesLink->GetFileStatus(array('Ticket'=>$ticket,'ProjectID'=>$pidobtained,'SourceLanguageID'=> "", 'TargetLanguageID'=> "",'FileID'=> "",'Filename'=>""));
$arrayPid = array();
foreach($fileStatus->GetFileStatusResult->FileStatuses->FileStatus as $fileStatusObtained)
{
$arrayPid = get_object_vars($fileStatusObtained);
//$arrayPid =$fileStatusObtained ;
}
echo is_array($arrayPid) ? 'Array' : 'not an Array';
echo "<br>";
echo("Count of array ".count($arrayPid));
echo "<br>";
print_r('<pre>'. print_r($arrayPid) .'</pre>');
This http://www.image-share.com/ijpg-1163-165.html is what i saw as a result.
Now since this Object has objects inside it along with the values i need i.e. FileID,FileName etc. I am seeing the error message but a glimpse of the output. The code i used was this (just a very minor change from the above. I used a foreach)
$fileStatus = $ServicesLink->GetFileStatus(array('Ticket'=>$ticket,'ProjectID'=>$pidobtained,'SourceLanguageID'=> "", 'TargetLanguageID'=> "",'FileID'=> "",'Filename'=>""));
$arrayPid = array();
foreach($fileStatus->GetFileStatusResult->FileStatuses->FileStatus as $fileStatusObtained)
{
$arrayPid = get_object_vars($fileStatusObtained);
//$arrayPid =$fileStatusObtained ;
}
echo is_array($arrayPid) ? 'Array' : 'not an Array';
echo "<br>";
echo("Count of array ".count($arrayPid));
echo "<br>";
//print_r('<pre>'. print_r($arrayPid) .'</pre>');
foreach($arrayPid as $val) {
echo ($val);
echo "<br>";
}
}
As a result of this i saw the following output http://www.image-share.com/ijpg-1163-166.html .
The index number 1 occupies the object and hence the error for string conversion.
If i use a For loop instead of the foreach in the code just above,i am unable to print the values.
I tried:
for($i=0;$i<(count($arrayPid));$i+=1)
{
echo($arrayPid[$i]);
}
But this would print nothing.
Could any one help me with a way so that i can iterate and have the values inside that array $arrayPid.
Would like to have your suggestions, views, doubts on the same.
I am sorry that i am using imageshare but that is the only way i can share my screens.
Thanks
Angie
The correct way to use it is:
foreach($fileStatus->GetFileStatusResult->FileStatuses->FileStatus as $fileStatusObtained)
{
$arrayPid = get_object_vars($fileStatusObtained);
//print_r($fileStatusObtained->FileID);
$fileId [] = $fileStatusObtained->FileID;
...
}

Categories