foreach in php iterates only through the first JSON - php

Please have a look at: http://codepad.org/uNlMsvwj for the json.
$json = json_decode($raw_json);
//print_r($json);
$count = count($json->response->results);
$i = 0;
foreach($json->response->results as $item){
echo($item->entries[$i]->displayname);echo "<br>";
echo($item->entries[$i]->location->street);echo " "; echo($item->entries[$i]->location->streetnumber);echo "<br>";
echo($item->entries[$i]->location->zipcode);echo " ";
echo($item->entries[$i]->location->city);echo "<br>";echo "<br>";
echo($item->entries[$i]->phonenumbers[0]->area);echo "/"; echo($item->entries[$i]->phonenumbers[0]->number);echo "<br>";
$i++;
}
The problem is that only the first elemet is printed. If i change $i manually with 1 i get the second.
I've been looking for 3 hours now and can't find a solution. Please forgive me if it is a beginner mistake.
Thanks
Update:
thank you all for your fast help

Did you mean to iterate over the results like so?
foreach($json->response->results as $item) {
for ($i = 0; $i < count($item->entries); $i++) {
echo($item->entries[$i]->displayname);echo "<br>";
echo($item->entries[$i]->location->street);echo " ";
echo($item->entries[$i]->location->streetnumber);echo "<br>";
echo($item->entries[$i]->location->zipcode);echo " ";
echo($item->entries[$i]->location->city);echo "<br>";echo "<br>";
echo($item->entries[$i]->phonenumbers[0]->area);echo "/";
echo($item->entries[$i]->phonenumbers[0]->number);echo "<br>";
}
}
Also, you can simplify your echo statements:
foreach($json->response->results as $item) {
for ($i = 0; $i < count($item->entries); $i++) {
echo $item->entries[$i]->displayname.'<br>';
echo $item->entries[$i]->location->street.' ';
echo $item->entries[$i]->location->streetnumber.'<br>';
echo $item->entries[$i]->location->zipcode.' ';
echo $item->entries[$i]->location->city.'<br><br>';
echo $item->entries[$i]->phonenumbers[0]->area.'/';
echo $item->entries[$i]->phonenumbers[0]->number.'<br>';
}
}

Try this one,it works I tested it:
foreach($json->response->results[0]->entries as $item){
echo($item->displayname);echo "<br>";
echo($item->location->street);echo " ";
echo($item->location->streetnumber);echo "<br>";
echo($item->location->zipcode);echo " ";
echo($item->location->city);echo "<br>";echo "<br>";
echo($item->phonenumbers[0]->area);echo "/"; echo($item->phonenumbers[0]->number);echo "<br>";
}

You should echo like this:
echo $item->entries[$i]->displayname . "<br>";
the . concatenates strings. Also echo doesn't use any ().

Change
foreach($json->response->results as $item){
to
foreach($json->response->results->entries as $item){
and these lines
echo($item->entries[$i]->displayname);echo "<br>";
to
echo $item->displayname . "<br>";
So your code will look like:
foreach($json->response->results->entries as $item){
echo "{$item->displayname}<br />";
echo "{$item->location->street} {$item->location->streetnumber}<br />";
echo "{$item->zipcode}<br />";
echo "{$item->location->city}<br /><br />";
echo "{$item->phonenumbers[0]->area}/{$item->phonenumbers[0]->number}<br />";
}

Try either for-loop instead of foreach:
$json = json_decode($raw_json);
//print_r($json);
$count = count($json->response->results);
foreach($json->response->results->entries as $item){
echo($item->displayname);echo "<br>";
echo($item->location->street);echo " ";
echo($item->location->streetnumber);echo "<br>";
echo($item->location->zipcode);echo " ";
echo($item->location->city);echo "<br>";echo "<br>";
echo($item->phonenumbers[0]->area);echo "/"; echo($item->phonenumbers[0]->number);echo "<br>";
}
...or include a for-loop inside the foreach:
$json = json_decode($raw_json);
//print_r($json);
$count = count($json->response->results);
foreach($json->response->results as $item){
for ($i = 0; $i < count($item->entries); $i++) {
echo($item->entries[$i]->displayname);echo "<br>";
echo($item->entries[$i]->location->street);echo " ";
echo($item->entries[$i]->location->streetnumber);echo "<br>";
echo($item->entries[$i]->location->zipcode);echo " ";
echo($item->entries[$i]->location->city);echo "<br>";echo "<br>";
echo($item->entries[$i]->phonenumbers[0]->area);echo "/";
echo($item->entries[$i]->phonenumbers[0]->number);echo "<br>";
}
}

Related

Illegal String Offset in Multidimensional Array

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];
}
?>

PHP variable is printing type not content

i've stucked for a while with php..
In my code:
for($i = 0; $i < $max;$i++){
if(//my condition){
$job_found.= $obj[$i];
}
else{
echo "jobs not found";
}
echo ($job_found);
}
When it gets a coincidence the results will be:
Array
But if i try:
print_r ($obj[1]);
The result will be:
Array ( [title] => my 2title [placement] => my placement [date] => my date [time] => My time [website] => http://www.g00gle.com )
How can i get the actual value of the array in that position and not just the type?
Thanks in advance
First, as you can see from your own Post, $obj[1] is an Array, which means that all the Elements in the $obj variable are most likely Arrays as well. Unfortunately, you cannot just echo an Array but iterate through it to get the echoable data like so:
<?php
$jobsHTML = "";
for($i = 0; $i < $max;$i++){
if(!$jobsStillExist){ // CONDITION TO CHECK IF JOBS STILL EXIST
echo "jobs not found";
continue;
}
// SINCE, $obj[$i] COULD BE AN ARRAY,
// YOU NEED TO CHECK THE TYPE 1ST.
// IF IT IS A STRING, APPEND IT AS A STRING TO $jobsHTML
// OTHERWISE, LOOP THROUGH IT TO GET IT'S CONTENT...
$foundJob = $obj[$i];
if(is_array($foundJob)){
foreach($foundJob as $jobData){
$jobsHTML .= $jobData["title"] . "<br />";
$jobsHTML .= $jobData["placement"] . "<br />";
$jobsHTML .= date("d/m/Y", strtotime($jobData["date"])) . "<br />";
$jobsHTML .= $jobData["time"] . "<br />";
$jobsHTML .= $jobData["website"] . "<br /><br />";
}
}else if(is_string($foundJob)){
$jobsHTML .= $foundJob . "<br /><br />";
}
}
echo ($jobsHTML);
$job_found=array();
for($i = 0; $i < $max;$i++){
if(//my condition){
$job_found[]= $obj[$i];
}
else{
echo "jobs not found";
}
}
print_r($job_found);
Can you try like this.

How to pass all the values in an array which is processed by for loop?

<?php
$xml = simplexml_load_file("sample.xml");
echo " ". $xml->getName() . "<br />";
foreach($xml->children()->children() as $child)
{
$a=$child->getName() . "<br />";
array_push($a);
echo $a;
}
?>
Try this
<?php
$arr = array();
$xml = simplexml_load_file("sample.xml");
echo " ". $xml->getName() . "<br />";
foreach($xml->children()->children() as $child)
{
$a=$child->getName() . "<br />";
$arr[] = $a;
echo $a;
}
?>

PHP: how to make a sum inside a "for each" cycle?

I've made a foreach loop that print some variables found in an xml file:
foreach ($xml->result->rowset->row as $row)
{
echo $row["price"] . " " . $row["product"] . "</br>";
}
I would like to get the sum of all the "prices" shown. How can i do?
Just have a variable add up those values as you iterate:
$total = 0; // start with zero
foreach ($xml->result->rowset->row as $row)
{
$total += $row["price"]; // add price to total
echo $row["price"] . " " . $row["product"] . "</br>";
}
echo $total; // echo out total amount
Store the count in a variable:
$total = 0;
foreach ($xml->result->rowset->row as $row) {
echo $row["price"] . " " . $row["product"] . "</br>";
$total += $row['price']; // assumed row_price is some integer
}
echo $total;
Simply add it to a new variable:
$sum = 0;
foreach ($xml->result->rowset->row as $row) {
echo $row["price"] . " " . $row["product"] . "<br />";
$sum += $row["price"];
}
echo $sum . "<br />";
$sum = 0;
foreach ($xml->result->rowset->row as $row)
{
echo $row["price"] . " " . $row["product"] . "</br>";
$sum += $row["price"] ;
}
echo $sum ;
isnt that simple ?
$sum=0;
foreach ($xml->result->rowset->row as $row)
{
echo $row["price"] . " " . $row["product"] . "</br>";
$sum +=$row["price"];
}
echo $sum;
just try this code!!

php json not showing Wunderground station list

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

Categories