API call to display json data - php

have a API call that gets JSON data with the following headers and info, need the php code that would display the below data in a table format:
the API call is: https://XXXXXXXXXXXXXXX.com/service/price/all?token=XXXXXXXXXXXXXXXXXXXXXXX
any help? I am a beginner.
[{"SKU":"CGP-15-GR-2017","Name":"2017 15 Grams Chinese Gold Panda Coin 200 Yuan BU Sealed","Metal":"Gold","ProductFamily":"Current Year Gold Coins","AssetClass":"Gold Bullion","Ounces":0.482315112540193,"Cogs":962.25,"Bid":907.52,"Ask":1042.34,"BaseCurrency":"USD","RetailShipping":0.0,"WholesaleShipping":0.0},{"SKU":"25-OZ-ATB-SET-2010","Name":"2010 America the Beautiful 5 oz Silver Bullion Coin Set","Metal":"Silver","ProductFamily":"ATB Bullion Program","AssetClass":"Silver Bullion","Ounces":25.0,"Cogs":779.16,"Bid":574.16,"Ask":1330.33,"BaseCurrency":"USD","Description":"25-OZ-ATB-SET-2010","RetailShipping":0.0,"WholesaleShipping":0.0},{"SKU":"PS-1-GR-PLAT-BAR","Name":"1 Gram Pamp Suisse Platinum Bar 999 Fine With Assay","Metal":"Platinum","ProductFamily":"Platinum Bullion","AssetClass":"Platinum","Ounces":0.03215,"Cogs":34.92,"Bid":27.6,"Ask":48.8,"BaseCurrency":"USD","Description":"1-PS-1-GR-PLAT-BAR","RetailShipping":0.0,"WholesaleShipping":0.0},{"SKU":"40-WQ-ROLL-BU","Name":"$10 Washington Quarters - 90% Silver 40-Coin Roll (BU)","Metal":"Silver","ProductFamily":"90% Junk Silver","AssetClass":"Silver Bullion","Ounces":7.15,"Cogs":165.64,"Bid":164.21,"Ask":234.67,"BaseCurrency":"USD","RetailShipping":0.0,"WholesaleShipping":0.0},{"SKU":"GIH-$10-NGCMS64-1932","Name":"GIH-$10-NGCMS64-1932","Metal":"Gold","ProductFamily":"Current Year Gold Coins","AssetClass":"Gold Bullion","Ounces":0.5,"Cogs":943.3,"Bid":990.8,"Ask":1865.03,"BaseCurrency":"USD","RetailShipping":0.0,"WholesaleShipping":0.0},{"SKU":"CGP-10th-2012","Name":"2012 1/10 oz Chinese Gold Panda Coin BU Sealed","Metal":"Gold","ProductFamily":"Current Year Gold Coins","AssetClass":"Gold Bullion","Ounces":0.1,"Cogs":222.62,"Bid":188.16,"Ask":387.52,"BaseCurrency":"USD","Description":"CGP-10th-2012","RetailShipping":0.0,"WholesaleShipping":0.0},{"SKU":"5-OZ-ATB--MBRNP-2020","Name":"2020 5 oz Silver ATB Marsh-Billings-Rockefeller National Park","Metal":"Silver","ProductFamily":"ATB Bullion Program","AssetClass":"Silver Bullion","Ounces":5.0,"Cogs":135.83,"Bid":114.83,"Ask":156.87,"BaseCurrency":"USD","RetailShipping":0.0,"WholesaleShipping":0.0},{"SKU":"SAK-Tenth-NGCPF69-2008","Name":"2008 South Africa 1/10 oz Gold Proof Krugerrand NGC PF 69 DCAM","Metal":"Gold","ProductFamily":"Current Year Gold Coins","AssetClass":"Gold Bullion","Ounces":0.1,"Cogs":188.66,"Bid":188.16,"Ask":279.41,"BaseCurrency":"USD","Description":"SAK-OUNCE-1977","RetailShipping":0.0,"WholesaleShipping":0.0},{"SKU":"1-OUNCE-AGE-1987","Name":"1987 1 oz Gold American Eagle Coin Brand New BU","Metal":"Gold","ProductFamily":"Current Year Gold Coins","AssetClass":"Gold

You can put the JSON data into an array and then iterate it with a foreach()
$arr = json_decode(JSON_DATA_FROM_API);//The data from your api
<table>
<tr>
<th scope="col">COL1</th>
<th scope="col">COL2</th>
<th scope="col">COL3</th>
<th scope="col">COl4</th>
</tr>
foreach($arr as $item) {
<tr>
<td>$item['SKU']</td>
<td>$item['Name']</td>
<td>$item['Metal']</td>
<td>$item['ProductFamily']</td>
</tr>
}
</table>

Related

php json_decode not working, json_last_error() thows 4

My English is poor. I'm sorry if there is anything rude.
Thank you for taking the time to read my question.
When I use PHP function json_decode(), i get null and json_last_error() throws 4.
Thanks for helping!
my PHP code is
$str = file_get_contents("cache.txt");
$str = htmlspecialchars_decode($str);
$arr = json_decode($str, true);
print_r($arr);
echo $errorinfo = json_last_error();
the content of File named cache.txt is:
[[1,[0,"wWfxgeyEgrRf1M",["https://encrypted-tbn0.gstatic.com/images?q\u003dtbn%3AANd9GcTFekou1VcAkVW23s69_Q53CsUJD0syjACwY0jHbRYcRIcr5cyp",225,225],["https://www.hijordan.com/image/cache/catalog/Jordan-Retro-1/Jordan-Retro-1-16-1080x1080.jpg",1080,1080],null,2,"rgb(160,42,51)",null,false,{"2001":[null,null,null,21,18,3,3,null,null,null,[]],"2003":[null,"M3A7LEiRdcA0DM","https://www.aljadid.com/efabshop/air-jordan-retro-1-red-black-white-p-16.html","Nike Air Jordan Retro 1 Red Black White - Buy Air Jordan 1 Retro ...",null,false,null,null,null,false,null,null,"Al Jadid",null,null,null,null,null,null,null,null,null,false,false,false,{"26":[null,2]}],"2006":[null,[4.0,null,"Air Jordan Retro 1 red black white",null,"A stepping stone to the world of Air Jordan is the Original air jordan 1 (I) White Black Red, which was worn by Michael Jordan the majority of the ...",null,true,5,60.85,"USD"]],"2008":[null,"Nike Air Jordan Retro 1 Red Black White ..."],"183836587":["aljadid.com"]}],null,[177,158,null,null,null,177,177,null,null,-10,null,null,false,true,null,null,[]],0,null,null,"wWfxgeyEgrRf1M",1,null,null,null,null,[[1580879352798185,178652430,3708684377],null,2]],[1,[0,"sFUMQKdZQFRaGM",["https://encrypted-tbn0.gstatic.com/images?q\u003dtbn%3AANd9GcSV5L3VvYWthX-IG9QO5QfLN_6eLvA687_og435LmF6_5NmGSI4",225,225],["https://www.hijordan.com/image/cache/catalog/air-jordan-12/air-jordan-12-49-1080x1080.jpg",1080,1080],null,2,"rgb(160,58,51)",null,false,{"2001":[null,null,null,21,18,3,6,null,null,null,[]],"2003":[null,"pTPqQEjGfZF7JM","https://togaf9-cert.opengroup.org/bcabshop/air-jordan-12-retro-black-varsity-red-p-1138.html","Air Jordan 12 Retro Black Varsity Red , Price: $89.90 - Air Jordan ...",null,false,null,null,null,false,null,null,"TOGAF? 9 Certification",null,null,null,null,null,null,null,null,null,false,false,false,{"26":[null,2]}],"2006":[null,[4.0,null,"Air Jordan 12 Retro Black Varsity Red","Nike","You should not miss the chance if you have not got one like the Air Jordan 12 Retro Black Varsity Red. Fine craftsmanship with premium materials like ...",null,true,5,89.9,"USD"]],"2008":[null,"Air Jordan 12 Retro Black Varsity Red ..."],"183836587":["togaf9-cert.opengroup.org"]}],],]

number_format every second number a img

I try to make a virutal money system and dont get the "number_format"
I want it like the number "7951753" and want that output:
795 17 53
Other example:
$money = 10001;
1 0 1
How I can make that?
You may use substr
$mynumber=7951753;
echo substr($mynumber, 0, 3)." Gold ". substr($mynumber, 3, 2)." Silver " . substr($mynumber, 5, 2)." Bronze ";
above code produces output:-
795 Gold 17 Silver 53 Bronze
You may do same with 10001 to get 1 Gold 0 Silver 1 Bronze :)
Have a try!
Sorry, display fail on posting that here:
Number: 7951753
Output: 795 Gold 17 Silver 53 Bronze
Other example:
Number: 10001
Output: 1 Gold 0 Silver 1 Bronze

Parsing feed that's inside namespace

I have tried several different approaches here, but to no avail. Can someone explain to me how the following type of feed can be parsed? Below is an excerpt
<?xml version='1.0'?>
<NoticeResults xmlns:sql="urn:schemas-microsoft-com:xml-sql">
<sql:query>
<Notice>
<PersonId>174171199</PersonId>
<NamePrefix></NamePrefix>
<NameAdditionalPrefix></NameAdditionalPrefix>
<FirstName>Donna</FirstName>
<MiddleName></MiddleName>
<LastName>Autrey</LastName>
<NameSuffix></NameSuffix>
<NameAdditionalSuffix></NameAdditionalSuffix>
<MaidenName></MaidenName>
<City></City>
<State>IL</State>
<Country>United States</Country>
<DateEntered>2015-02-17T00:00:00</DateEntered>
<DateCompleted>2015-02-17T00:00:00</DateCompleted>
<DateExpired>2015-03-19T00:00:00</DateExpired>
<NoticeText><p><B>PEKIN </B>- Donna Lou (Morris) Autrey, 83, of Pekin passed away at 1:10 p.m. Sunday, Feb. 15, 2015, at Autumn Accolade in Green Valley.</p><p>A graveside service will be at 11 a.m. Thursday at Lakeside Cemetery. There will be no visitation. Preston-Hanley Funeral Homes &amp; Crematory is in charge of arrangements.</p>
</NoticeText>
<NoticeType>Courtesy</NoticeType>
<Status>Active</Status>
<FromToYears></FromToYears>
<AffiliateSite>PJStar</AffiliateSite>
<AffiliateAdId>Autrey_02/17/2015_4673625</AffiliateAdId>
<PublishedBy>Peoria Journal Star</PublishedBy>
<DisplayURL>http://www.legacy.com/Link.asp?I=LS000174171199</DisplayURL>
<LocationList></LocationList>
<ShowInSpotlight>0</ShowInSpotlight>
<DateCreated>2015-02-17T01:12:37.510</DateCreated>
<RowVersion>793618506</RowVersion>
<GuestBookURL></GuestBookURL>
</Notice>
<Notice>
<PersonId>174171209</PersonId>
<NamePrefix></NamePrefix>
<NameAdditionalPrefix></NameAdditionalPrefix>
<FirstName>Lois</FirstName>
<MiddleName></MiddleName>
<LastName>Barden</LastName>
<NameSuffix></NameSuffix>
<NameAdditionalSuffix></NameAdditionalSuffix>
<MaidenName></MaidenName>
<City>Peoria</City>
<State>IL</State>
<Country>United States</Country>
<DateEntered>2015-02-17T00:00:00</DateEntered>
<DateCompleted>2015-02-17T00:00:00</DateCompleted>
<DateExpired>2015-03-19T00:00:00</DateExpired>
<NoticeText><img src="/Images/Cobrands/PJStar/Photos/C7KC6NVUW02_021715.jpg" align="left" border="0" vspace="4" hspace="10" lgyOrigName="C7KC6NVUW02.jpg"><p><B>PEORIA </B>- Lois Mae Barden, age 84, of Peoria passed away Sunday, Feb. 15, 2015, at OSF Saint Francis Medical Center in Peoria.</p><p>Lois was born on Sept. 12, 1930, in Macomb, Ill. She married James W. Barden on June 12, 1948, in Peoria. He preceded her in death in June of 1988. </p><p>She also was preceded in death by her parents and 12 siblings.</p><p>Surviving are her children, Kathy (Ted) Kindred of Manito, Ill., Lynn (Allen) Simer of Nineveh, Ind., and Jim (Deb) Barden of North Pekin, Ill.; four grandchildren; six great-grandchildren; one great-great-grandson; and her two sisters, Doris Butts and Maggie Hoyt.</p><p>Lois enjoyed spending time at home with her family. She was always there to care for them when they were in need. She also enjoyed listening to Christian music, crafting, cooking and crocheting.</p><p>A visitation will be from 1 to 2 p.m. Thursday, Feb. 19, 2015, at Davison-Fulton Woodland Chapel in Peoria. Burial will follow at Swan Lake Memory Gardens in Peoria. </p><p>Memorials may be made to Illinois Cancer Care.</p><p>Online condolences may be made through <a href="http://www.davison-fulton.com" target="_new" rel="nofollow">www.davison-fulton.com</a>.</p><center><br><a rel="nofollow" href="http://www.davison-fulton.com" target="_blank"><img src="/Images/Cobrands/PJStar/Logos/www.davison-fulton.com.jpg" border="0"></a></center>
</NoticeText>
<NoticeType>Paid</NoticeType>
<Status>Active</Status>
<FromToYears></FromToYears>
<AffiliateSite>PJStar</AffiliateSite>
<AffiliateAdId>Barden_02/17/2015_102257420</AffiliateAdId>
<PublishedBy>Peoria Journal Star</PublishedBy>
<DisplayURL>http://www.legacy.com/Link.asp?I=LS000174171209</DisplayURL>
<LocationList></LocationList>
<FHIndex>10868</FHIndex>
<FHName>Davison-Fulton Woodland Chapel</FHName>
<FHKnownByName1>Davison-Fulton Woodland Chapel</FHKnownByName1>
<FHAddressLine1>2021 North University Street</FHAddressLine1>
<FHCity>Peoria</FHCity>
<FHStateProvince>IL </FHStateProvince>
<FHZipCode>61604 </FHZipCode>
<FHPhoneNumber1>3096885700 </FHPhoneNumber1>
<FHUrl>www.davison-fulton.com</FHUrl>
<ShowInSpotlight>0</ShowInSpotlight>
<DateCreated>2015-02-17T01:13:01.857</DateCreated>
<ImageUrl>http://mi-cache.legacy.com/legacy/images/Cobrands/PJStar/Photos/C7KC6NVUW02_021715.jpg</ImageUrl>
<RowVersion>793622447</RowVersion>
<GuestBookURL>http://www.legacy.com/Link.asp?I=GB000174171209</GuestBookURL>
</Notice>
</sql:query>
</NoticeResults>
I have been banging my head against the table on this all day (huge waste of 8 hours). All we have to work with in our offices are PHP (limitation by our CMS). Can someone please explain how I would go about parsing through a feed like this? I've gotten pretty far, but still can't seem to figure this out. Please also explain why you do whatever you do in order to make this work. I'll have to parse several feeds structured this way and i've never dealt with this before. Any help will be greatly appreciated.
Thanks!
Chris
You can access the elements using DOM Extension. There is an example of looping through XML from w3schools.
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("doc.xml");
$x = $xmlDoc->documentElement;
foreach ($x->childNodes AS $item) {
// Do whatever is needed
}
?>

PHP, Memory and Iteration

I've been noticing some odd behavior while experimenting with benchmarking SplFixedArrays. Take this little snippet of code, for instance...
<?php
$splFixedArray = new \SplFixedArray( 100000 );
echo number_format( memory_get_usage() ) . PHP_EOL;
$variable = 'Truffaut single-origin coffee wayfarers, church-key asymmetrical 90\'s trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PBR fingerstache Bushwick Cosby sweater. McSweeney\'s mumblecore semiotics, twee quinoa tofu +1 fingerstache pop-up. Echo Park bitters disrupt irony. Truffaut single-origin coffee wayfarers, church-key asymmetrical 90\'s trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PBR fingerstache Bushwick Cosby sweater.';
var_dump( $variable );
for( $i = 0; $i < 100000; $i++ )
{
$splFixedArray[ $i ] = $variable;
}
echo number_format( memory_get_usage() );
Which outputs...
1,032,080
string(1209) "Truffaut single-origin coffee wayfarers, church-key asymmetrical 90's trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PB"...
1,032,384
Now, let's add a simple random integer onto the end while in the for loop...
<?php
$splFixedArray = new \SplFixedArray( 100000 );
echo number_format( memory_get_usage() ) . PHP_EOL;
$variable = 'Truffaut single-origin coffee wayfarers, church-key asymmetrical 90\'s trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PBR fingerstache Bushwick Cosby sweater. McSweeney\'s mumblecore semiotics, twee quinoa tofu +1 fingerstache pop-up. Echo Park bitters disrupt irony. Truffaut single-origin coffee wayfarers, church-key asymmetrical 90\'s trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PBR fingerstache Bushwick Cosby sweater.';
var_dump( $variable );
for( $i = 0; $i < 100000; $i++ )
{
$splFixedArray[ $i ] = $variable . rand();
}
echo number_format( memory_get_usage() );
Which results in this...
1,034,320
string(1209) "Truffaut single-origin coffee wayfarers, church-key asymmetrical 90's trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PB"...
129,834,272
What I'm curious about is why function calls are resulting in stacked memory usage. Is it normal that memory would not be freed up after the iteration?
This behavior is expected.
In the first case, you are storing the same value multiple times, which can be implemented as a single instance of the value and a batch of references to it, with a copy-on-write semantic for cases when the value at a given array index is changed.
In the second case, you are storing many different values, which can't be handled the same way; memory must be allocated for the full contents of each value, which results in the difference you see in memory consumption between the two cases.

Difficult algorithm: badge balancing, math distribution

I have a quite interesting problem that's making my head twist. I'm working on a small system consisting of users and awards (called badges). There is a special badge that is awarded to users depending on the following criteria: 10 bronze badges, 5 silver badges and 1 gold badge. That is pretty simple, however, if an user has 8 bronze badges, 7 silver badges and 1 gold badge, he can use his 2 additional silver badges as bronze ones.
This happens everytime the user has available "higher" badges to distribute. Again, for example, if he has 8 bronze badges, 4 silver badges and 4 gold badges, he can "transform" 2 of his gold badges into bronze and 1 to silver, in order to earn the special badge.
I have absolutely no idea of how to do this. I've tried with various loops, ifs, but i can never distribute properly. Maybe someone can help me out?
The user needs at least 1 gold badge, at least 6 badges that are either silver or gold, and at least 16 badges that are bronze, silver or gold.
The pseudocode is
count(gold) >= 1
&& count(gold) + count(silver) >= 6
&& count(gold) + count(silver) + count(bronze) >= 16
If you also have a diamond medal that can swap for a gold, silver or bronze then include that as well, like
count(diamond) + count(gold) >= 1
&& count(diamond) + count(gold) + count(silver) >= 6
// etc
Or you could use a 'medal rank' so that you can do something simpler like
count(rank of gold or higher) >= 1
&& count(rank of silver or higher) >= 6
&& count(rank of bronze or higher) >= 16
$bank['g'] -= $price['g'];
$bank['s'] -= $price['s'];
$bank['b'] -= $price['b'];
if ($bank['b'] < 0) {
$bank['s'] += $bank['b'];
$bank['b'] = 0;
}
if ($bank['s'] < 0) {
$bank['g'] += $bank['s'];
$bank['s'] = 0;
}
if ($bank['g'] < 0) {
//not enough cash
} else {
//ok
}
One way would be to start with the "highest" badge, subtract the number that are required, and convert the rest to the next badge. So:
Take away one gold badge.
Convert all remaining gold badges to silver.
Take away five silver badges.
Convert all remaining silver badges to bronze.
Take away 10 bronze badges.
If any of the "take away" steps fails, then they don't qualify for the badge. This is simple and it's trivial to modify it for other badge quantities or exchange rates.

Categories