I am trying to display each item in a JSON array of reviews. There are two reviews in the array, but instead of displaying both of them, this code displays same one twice.
Why is this happening?
$response = curl_exec($curl);
$data = json_decode($response, true);
// Setup the Review for posting to the Mysql Database
// Loop through Reviews
for ($i=0; $i<count($data['reviews']); $i++) {
$id = $data['reviews']['0']['id']; // good
$stars = $data['reviews']['0']['stars']; //good
$title = $data['reviews']['0']['title'];
$text = $data['reviews']['0']['text'];
$createdAt = $data['reviews']['0']['createdAt'];
$companyReply = $data['reviews']['0']['companyReply']['text'];
$companyReplyDate = $data['reviews']['0']['companyReply']['createdAt'];
// Do Mysql insert for each row
// show this
echo "id: " . $id . "</br>";
echo "stars: " . $stars . "</br>";
echo "title: " . $title . "</br>";
echo "text: " . $text . "</br>";
echo "Created: " . $createdAt . "</br>";
echo "Reply: " . $companyReply . "</br>";
echo "Reply Date: " . $companyReplyDate . "</br> </br>";
}
curl_close($curl);
It is because you aren't actually using your loop increment variable to get different array keys. You're just selecting the ['0'] index repeatedly. Instead, use $i as the array key like this:
for ($i=0; $i<count($data['reviews']); $i++) {
$id = $data['reviews'][$i]['id']; // good
$stars = $data['reviews'][$i]['stars']; //good
$title = $data['reviews'][$i]['title'];
$text = $data['reviews'][$i]['text'];
$createdAt = $data['reviews'][$i]['createdAt'];
$companyReply = $data['reviews'][$i]['companyReply']['text'];
$companyReplyDate = $data['reviews'][$i]['companyReply']['createdAt'];
// ... etc.
Related
I am attempting to fetch a JSON file from a separate website, read that file and then decode it into a multidimensional array. So far at that point it seems to work. However, when I try and break it all down into variables to echo, it goes wrong when its 4 levels deep. You can see the actual JSON file from the link in the PHP code and below is the PHP Code I am using. The specific variables that have problems are $prices in 2 areas and $rulings. Any help someone can provide with this would be appreciated.
<?php
$path = 'https://www.mtgjson.com/json/LEA.json';
$FileContents = file_get_contents($path);
$cards = json_decode($FileContents, true);
foreach ($cards['cards'] as $mtgcard){
$Artist = $mtgcard['artist'];
$borderColor = $mtgcard['borderColor'];
$colorIdentity = $mtgcard['colorIdentity'][0];
$Colors = $mtgcard['colors'][0];
$convertedManaCost = $mtgcard['convertedManaCost'];
$edhrecRank = $mtgcard['edhrecRank'];
$flavorText = $mtgcard['flavorText'];
$cards_foreignData = implode($mtgcard['foreignData'],",");
$foreignData = explode(',', $cards_foreignData);
$frameVersion = $mtgcard['frameVersion'];
$hasFoil = $mtgcard['hasFoil'];
$hasNonFoil = $mtgcard['hasNonFoil'];
$isPaper = $mtgcard['isPaper'];
$Layout = $mtgcard['layout'];
$cards_legalities = implode($mtgcard['legalities'],",");
$legalities = explode(',', $cards_legalities);
$manaCost = $mtgcard['manaCost'];
$mcmId = $mtgcard['mcmId'];
$mcmMetaId = $mtgcard['mcmMetaId'];
$mtgstocksId = $mtgcard['mtgstocksId'];
$multiverseId = $mtgcard['multiverseId'];
$name = $mtgcard['name'];
$number = $mtgcard['number'];
$originalText = $mtgcard['originalText'];
$originalType = $mtgcard['originalType'];
$power = $mtgcard['power'];
$cards_prices = implode($mtgcard['prices'],",");
$prices = explode(',', $cards_prices);
$cards_prices_2 = implode($cards_prices['paper'],",");
$prices_2 = explode(',', $cards_prices_2);
$cards_printings = implode($mtgcard['printings'],",");
$printings = explode(',', $cards_printings);
$cards_purchaseUrls = implode($mtgcard['purchaseUrls'],",");
$purchaseUrls = explode(',', $cards_purchaseUrls);
$rarity = $mtgcard['rarity'];
$cards_rulings = implode($mtgcard['rulings'],",");
$rulings = explode(',', $cards_rulings);
$scryfallId = $mtgcard['scryfallId'];
$scryfallIllustrationId = $mtgcard['scryfallIllustrationId'];
$scryfallOracleId = $mtgcard['scryfallOracleId'];
$cards_subtypes = implode($mtgcard['subtypes'],",");
$subtypes = explode(',', $cards_subtypes);
$cards_supertypes = implode($mtgcard['supertypes'],",");
$supertypes = explode(',', $cards_supertypes);
$tcgplayerProductId = $mtgcard['tcgplayerProductId'];
$text = $mtgcard['text'];
$toughness = $mtgcard['toughness'];
$type = $mtgcard['type'];
$types = $mtgcard['types'][0];
$uuid = $mtgcard['uuid'];
$a = substr($scryfallId, 0, 1);
$b = substr($scryfallId, 1, 1);
$convert = "<img src='https://img.scryfall.com/cards/large/front/" .$a. "/" .$b. "/" .$scryfallId. ".jpg' />";
echo $convert;
echo "Artist Name: " .$Artist. "<br/>";
echo "Border Color: " .$borderColor. "<br/>";
echo "colorIdentity: " .$colorIdentity. "<br/>";
echo "Colors: " .$Colors. "<br/>";
echo "convertedManaCost: " .$convertedManaCost. "<br/>";
echo "edhrecRank: " .$edhrecRank. "<br/>";
echo "flavorText: " .$flavorText. "<br/>";
echo "foreignData: " .$foreignData[0]. "<br/>";
echo "frameVersion: " .$frameVersion. "<br/>";
echo "hasFoil: " .$hasFoil. "<br/>";
echo "hasNonFoil: " .$hasNonFoil. "<br/>";
echo "isPaper: " .$isPaper. "<br/>";
echo "Layout: " .$Layout. "<br/>";
echo "Brawl: " .$legalities[0]. "<br/>";
echo "Commander: " .$legalities[1]. "<br/>";
echo "Duel: " .$legalities[2]. "<br/>";
echo "Future: " .$legalities[3]. "<br/>";
echo "Historic: " .$legalities[4]. "<br/>";
echo "Legacy: " .$legalities[5]. "<br/>";
echo "Modern: " .$legalities[6]. "<br/>";
echo "Oldschool: " .$legalities[7]. "<br/>";
echo "Penny: " .$legalities[8]. "<br/>";
echo "Pioneer: " .$legalities[9]. "<br/>";
echo "Standard: " .$legalities[10]. "<br/>";
echo "Vintage: " .$legalities[11]. "<br/>";
echo "Manacost: " .$manaCost. "<br/>";
echo "mcmId: " .$mcmId. "<br/>";
echo "mcmMetaId: " .$mcmMetaId. "<br/>";
echo "mtgstocksId: " .$mtgstocksId. "<br/>";
echo "multiverseId: " .$multiverseId. "<br/>";
echo "name: " .$name. "<br/>";
echo "number: " .$number. "<br/>";
echo "originaltext: " .$originalText. "<br/>";
echo "originaltype: " .$originalType. "<br/>";
echo "power: " .$power. "<br/>";
echo "MTGO prices: " .$prices[0]. "<br/>";
echo "MTGO Foil Prices: " .$prices[1]. "<br/>";
echo "Paper Prices: " .prices[2] "<br/>"; <- 4 levels deep doesnt work
echo "Paper Foil Prices: " .$prices[3]. "<br/>"; <- 4 levels deep doesnt work
echo "purchaseUrls: " .$purchaseUrls[0]. "<br/>";
echo "purchaseUrls: " .$purchaseUrls[1]. "<br/>";
echo "purchaseUrls: " .$purchaseUrls[2]. "<br/>";
echo "rarity: " .$rarity. "<br/>";
echo "ruling: " .$rulings['date'].$rulings['text'] "<br/>"; <-- 4 levels deep doesnt work
echo "scryfallId: " .$scryfallId. "<br/>";
echo "scryfallIllustrationId: " .$scryfallIllustrationId. "<br/>";
echo "scryfallOracleId: " .$scryfallOracleId. "<br/>";
echo "subtypes: " .$subtypes[0]. "<br/>";
echo "supertypes: " .$supertypes[0]. "<br/>";
echo "tcgplayerProductId: " .$tcgplayerProductId. "<br/>";
echo "text: " .$text. "<br/>";
echo "toughness: " .$toughness. "<br/>";
echo "type: " .$type. "<br/>";
echo "types: " .$types. "<br/>";
echo "uuid: " .$uuid. "<br/>";
}
?>
You should mention the array name to fetch the content inside array, here is the example code and artist is with small "a" not capital
Edit as per comment request
Get the array of 'legalities' a string with , separated using implode and than explode with , and convert into an array to print those
Note: only the values will be imported using implode not the keys
<?php
// error_reporting(0);
// header('Content-type: application/json');
$path = 'https://www.mtgjson.com/json/LEA.json';
$FileContents = file_get_contents($path);
$cards = json_decode($FileContents, true);
foreach($cards['cards'] as $mtgcard) {
echo '<br>' .$course_data1 = $mtgcard['artist'];
$cards_legalities = implode($mtgcard['legalities'],",");
$myArray = explode(',', $cards_legalities);
echo $myArray[0];// 1st array
//Multidimensional Array for your updated question
$cards_prices_paper = implode($mtgcard['prices']['paper'],",");
$prices_paper_array = explode(',', $cards_prices_paper);
echo $prices_paper_array[0];
$rulings_date = implode(', ', array_column($mtgcard['rulings'], 'date'));
$rulings_date_array = explode(",", $rulings_date);
echo $rulings_date_array[0];
}
?>
I am so close to figuring this out, this is using Wordpress and Gravity Forms Plugin:
<?php
$form_id = '1'; // The registration form's ID
$entries = GFAPI::get_entries( $form_id ); // Get all entries
$html = "<table class='ent'>"; // Create an HTML table
$html .= "<tr><th>Name</th><th>Organization</th><th>Event</th><th>Date</th><th>Number Attending</th></tr>";
$list = array(); // Array to store the original fields
$used = array(); // Array to stored the "used" fields
// Loop through array of entries,each element
foreach($entries as $entry){
// Get datepart from datetime of event and today's date
$date = date_format(new DateTime($entry['8']), 'Y-m-d');
$today = date("Y-m-d");
// Compare event's date with current date
if ( $date >= $today ) {
$list[] = $entry;
if (!empty($used[$entry['6']])) // If used[event name] not null then sum associated numattend
{
$used[$entry['6']] += $entry['5'];
}
else // return associated numattend
{
$used[$entry['6']] = $entry['5'];
}
}
}
unset($entry);
foreach ($used as $key => $value) {
foreach ($list as $key1 => $value1) {
$html .= "<tr><td>" . $value1['1'] . " " . $value1['2'] . "</td><td>" . $value1['93'] . "</td><td>" . $value1['6'] . "</td><td>" . $value1['8'] . "</td><td>" . $value1['5'] . "</td></tr>";
}
$html .= "<tr class='ent_sum_rw'><td>" . " " . "</td><td>" . " " . "</td><td>" . " " . "</td><td class='ent_sum'>" . "Total Attending:" . "</td><td>" . $value . "</td></tr>";
}
unset($value);
$html .= "</table>";
return $html;
?>
Result:
I want the loop to end the entry list on the corresponding "Event Name", Like "Test Event 22" should not show up on the top entry list.
The trick is to populate an Array that meets your demands and after that convert it to html. I haven't tested the code, but it should be clear how it works.
$aEventList = Array();
foreach($entries as $entry){
if (!isset($aEventList[$entry['7']])){ //7 is id of event
//if this event is not made, create it and add name and the date, enter the right numeral
$aEventList[$entry['7']]['name'] = $entry['6'];
$aEventList[$entry['7']]['date'] = $entry['90'];
$aEventList[$entry['7']]['users'] = Array();
}
$aEventList[$entry['7']]['users'][] = Array('name' => $entry['1'] . ' '. $entry['2'],
'org' => $entry['93'],
'num' => $entry['5']);
}
//now you've populated every event and you can loop through it on your desired way:
foreach ($aEventList as $iEvent => $aEvent){
echo $aEvent['name']; //event name
echo $aEvent['date']; // event date
foreach ($aEvent['users'] as $aEventUser){
echo $aEventUser['name']; // user name
echo $aEventUser['org']; // user organisation
echo $aEventUser['num']; // num attendees
}
}
$qua1 = "5";
$queryNotification= "SELECT * from stock where stockQty <= :qua1 ";
$stmt3 = $conn->prepare($queryNotification);
$stmt3->bindParam(':qua1',$qua1);
$stmt3->execute();
while ($queryNotRow = $stmt3->fetch()){
$a=array("Qty"=>$queryNotRow['stockQty'],"name "=>$queryNotRow['stockName'],"cb "=>$queryNotRow['stockPrice']);
// $array[$queryNotRow['stockQty']] = $queryNotRow['stockName'];
foreach( $a as $row ):
$b = "stockqty = " . $queryNotRow['stockQty'] . " and StockName = " . $queryNotRow['stockName'] . "<br>";
endforeach;
echo $b;
}
If I add send email code inside the foreach loop , the system will send many email according on how many data. How can I only send all the data by ONE EMAIL??
$a=array("Qty"=>$queryNotRow['stockQty'],"name "=>$queryNotRow['stockName']);
foreach($a as $key=>$data){
echo 'stock'.$key.'='.$data.'<br/>';
}
foreach( $a as $row ):
echo "stockqty = " . $row['Qty'] . " and StockName = " . $row['name'] . "<br>";
endforeach;
try this,
$a[] = array(
"Qty" => 1,
"name " => 2
);
foreach ($a as $row) {
echo $row['Qty']."===".$row['name'];
}
I'm trying to show a list of all nearby weather stations.
I have the code:
$json_string = file_get_contents("http://api.wunderground.com/api/8b19ccf6a06c0826/geolookup/conditions/q/Netherlands/Rotterdam.json");
$parsed_json = json_decode($json_string);
$stations = $parsed_json->{'location'}->{'nearby_weather_stations'}->{'pws'}->{'station'};
$count = count($stations);
for($i = 0; $i < $count; $i++)
{
$station = $stations[$i];
if (count($station) > 1)
{
echo "City: " . $station->{'city'} . "\n";
echo "State: " . $station->{'state'} . "\n";
echo "Latitude: " . $station->{'lat'} . "\n";
echo "Longitude: " . $station->{'lon'} . "\n";
}
}
But currently it's not showing anything, i have searched for examples but i couldn't find any solution fot this problem.
Alternatively, you could use a simple foreach to iterate those values. Consider this example:
$json_string = file_get_contents("http://api.wunderground.com/api/8b19ccf6a06c0826/geolookup/conditions/q/Netherlands/Rotterdam.json");
$parsed_json = json_decode($json_string, true); // <-- second parameter to TRUE to use it as an array
$desired_values = $parsed_json['location']['nearby_weather_stations']['pws']['station'];
foreach($desired_values as $key => $value) {
echo "<hr/>";
echo "City: " . $value['city'] . "<br/>";
echo "State: " . $value['state'] . "<br/>";
echo "Latitude: " . $value['lat'] . "<br/>";
echo "Longitude: " . $value['lon'] . "<br/>";
echo "<hr/>";
}
Sample Fiddle
I'm working on an online menu ordering system and I wanted to filter the data according to its category. I've tried to make it work with this code but it's only displaying one category.
**<li><?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?> Scotch/Bourbon</a></li>
<li><?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?> Brandy/Cognac</a></li>
<li><?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?> Vodka/Gin/Tequila/Apertifs/Liqueur</a></li><br>
<li><?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?> Beer/Softdrinks</a></li>
<li><?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?> Cocktails</a></li>**
^ basically these are the categories and below is how display them.
**
<?php
$category = $_GET['choice'];
$category = str_replace('%', ' ', $category);
$query = "SELECT * FROM product_drinks WHERE drinks_cat = '" . $category . "'";
$result = mysql_query($query);
$total_records = mysql_num_rows($result); // the number of records in your result set
$num_cols = 2; // the number of columns
$num_rows = ceil($total_records / $num_cols); // the number of rows
$num = 0; // don't change this value, this is the first number of each record inside a record set
echo "<table style= 'cellpadding:8 width:100'>\n";
// next the loop for the table rows
for ($rows = 0; $rows < $num_rows; $rows++) {
echo "<tr bgcolor='black'>\n";
// this is the loop for the table columns
for ($cols = 0; $cols < $num_cols; $cols++) {
if ($num < $total_records) { // show records if available (reduce by one because the first record is no. "0" (zero)
// first create variables with the values of the current record
$title = mysql_result($result, $num, "drinks_name");
$clean_name = str_replace('_', ' ', $title);
$price = mysql_result($result, $num, "drinks_shot");
$price2 = mysql_result($result, $num, "drinks_bottle");
$category = mysql_result($result, $num, "drinks_cat");
$description = mysql_result($result, $num, "drinks_image");
$title = str_replace(' ', '%', $title);
echo "<td class='label'><a class='fancybox fancybox.ajax' href='food.php?drink=" . $title . "'>
<img src='" . mysql_result($result, $num, 'drinks_image') . "' class='masterTooltip' title= '" . $category . "'</a><br>";
echo "<td style='width:50%' class='desc'><b>" . $clean_name . "</b><br> Shot:<font style='color:#0072bc'> Php " . $price . "</font><br> Bottle: <font style='color:#724c0e'>Php " . $price2 . "</font></td>\n";
} else { // show an empty cell
echo "<td> </td>\n";
}
$num++; // raise the number by one for the next record
}
echo "</tr>\n"; // there are no more cols in this row, close the table row tag
}
echo "</table>\n"; // end of the region = closing tag for the table element
?>
**
I wish I could get over this wall. Please help~
First things first.
<?php echo "<a href='clubmarumenu.php?choice=".$category."'>"?>
In the first chunk of code, you are using the same variable for all the links.
Are you passing different values for $category here. I believe you are not! and hence all the links are pointing to the same url.
You should use urldecode instead of str_replace('%', ' ', $category). (http://in2.php.net/urldecode)
Please indent your code so that it can be read and understood easily :)