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>';
}
Related
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.
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
I have a PHP session array where it can be counted as multidimensional array, basically I am trying to store data inside my session array and i am successfully obtaining that part of the task. The main issue is, I am not able to echo them specifically and I have to use var_dump. When I try to print them with echo i got an notice which says array to string conversion. Please any help I would be appreciated how to print them with their own specific keys or values. The code as follows:
if (!is_array($_SESSION['products']['names'])){
$_SESSION['products']['names'] = array();
$_SESSION['products']['names']['prices']= array();
}else {
$pros = $_SESSION['products']['names'];
if (in_array($product->getName(), $pros, true)){
echo 'The product is available in your basket';
} else {
array_push($_SESSION['products']['names'],$product->getName());
array_push($_SESSION['products']['names']['prices'], $product->getPrice(Currency::getCurrentCurrency()));
foreach ($_SESSION['products'] as $val){
echo $val['names'];
echo $val['prices'];
}
}
}
The output that I receive as follows:
Notice: Undefined index: names in
Array to string conversion in
Use join() function in your foreach, like this:
echo join('<br>', $val);
Or instead of
echo $val['prices'];
write
echo $val['names']['prices'];
This is your problem...
// Here your assigning `['names']` as a string..
array_push($_SESSION['products']['names'],$product->getName());
// Then here you're overwriting the string with an array...
array_push($_SESSION['products']['names']['prices'], $product->getPrice(Currency::getCurrentCurrency()));
Change the first one to this..
array_push($_SESSION['products']['names']['name'],$product->getName());
Assuming $product->getPrice() returns a string or a number...
foreach ($_SESSION['products'] as $val){
foreach($val['names'] as $name){
echo $name['name'];
echo $name['prices'];
}
}
There is no issue with the code you have here. I don't see you trying to echo or vardump them directly so please show the code you are echoing them out specifically or the output from above and which line is giving you an issue.
If you want to echo each one out with it's price.
for($i=0;$i<count($_SESSION['products']['names']);$i++) {
echo $_SESSION['products']['names'][$i] . " " . $_SESSION['products']['names']['price'][$i];
}
Hi am trying to read a directory for html files and put them in array and retrieve one by one.
i used following code
$filelist = glob($directory."/*.html");
$val=natsort($filelist); // Sort the array
foreach($filelist as $key => $value)
{
echo " $value , ";
}
$next=0;
$ns=$next+"1";
$filelist1=$filelist[$ns];
echo $filelist1;
am getting html files in a array but not able to retrieve one by one
please suggest
Thanks
That's echoing each item, not returning an array. Maybe it would be more clear if you change
echo " $value , ";
to
echo "ITEM $value ENDITEM , ";
Works for me
$directory = "./dir";
$filelist = glob($directory."/*.html");
sort($filelist);
foreach ($filelist as $filename) {
echo "$filename, ";
}
Also you may use
echo implode(', ', $filelist);
Instead of foreach
Return result like this:
./dir/christmas_en.html, ./dir/christmas_fr.html, ./dir/etpl_winphone.html,
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;
...
}