foreach results as feed_url - php

I'm trying to get the result of my foreach loop into an url to do a simplexml_load_file with.
So it goes like this:
(...) //SimpleXML_load_file to get $feed1
$x=1;
$count=$feed1->Count; //get a count for total number of loop from XML
foreach ($feed1->IdList->Id as $item1){
echo $item1;
if($count > $x) {
echo ',';} //Because I need coma after every Id, except the last one.
$x++;
}
The two echo are just to see the result. It gives me something like:
22927669,22039496,21326191,18396266,18295747,17360921,15705350,15681025,15254092,12939407,11943825,11495650,10964843
I would like to put that in a url to make a simplexml_load_file just like that
$feed_url = 'http://www.whatevergoeshere'. $RESULT_OF_FOREACH . 'someothertext';
So it would look like:
$feed_url = 'http://www.whatevergoeshere22927669,22039496,21326191,18396266,18295747,17360921,15705350,15681025,15254092,12939407,11943825,11495650,10964843someothertext';
I've try to store it into an array or a function and then call it into the feed_url but it did not work the way I tried it.
I hope it's clear, I'll answer fast to questions if not.
Thanks.

It's really difficult to make out what you want, so I'm going to guess you want to store the list as a comma delimited string in a variable. the easiest way is to implode the array of ids
$ids = array();
foreach ($feed1->IdList->Id as $item1){
$ids[] = (string) $item1;
}
$RESULT_OF_FOREACH = implode(',', $ids);
$feed_url = 'http://www.whatevergoeshere'. $RESULT_OF_FOREACH . 'someothertext';

Related

PHP cURL string get everything before and after certain part of string

Im usin cURL to crabb some data from webpage.
But as the data is array based, but the size changes and varies.
Then i need to search for parts of string and want to get everyhting after the
part til next comma.
{"id":2988001,"teatiseNr":"50000099027","mkood":74,
Now here is the string.
I would only like to have everything after {"id":
til the first comma.
So my output would be 2988001
Why i need the search criteria is because some times there are more variables and that messes up the order.
Right now im using simple
$pieces = explode(",", $page);
And then just delete the rest with
str_replace('{"id":','',$pieces[0]);
There must be more elegant way to make this work.
this is a json string, so you can simply do:
$data = json_decode($string);
echo $data->id;
If it is array based then alistaircol, matei, and neil are right you should use something like
$data = json_decode($page);
$id = $data->id
Let's say for some reason the response actually not JSON and the order of the item with id is variable then something like this could work too
$no_braces = str_ireplace('{','',$page);
$no_quotes = str_ireplace('"','',$no_braces);
$items = explode(",",$no_quotes);
function getID($items){
foreach($items as $item){
$parts = explode($item, ':');
$key = $parts[0];
if($key === 'id'){
return $parts[1];
}
}
return null;
}

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

PHP: String in json parse

I am trying to parse a json. I am running this in a foreach loop and if I do the following it works:
$places = array('restaurant', 'store', 'etc')
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->restaurant[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->restaurant[0]->geometry->location->lng;
}
However, when I do the following, i.e. I change restaurant to $places (I need to do this since I have an array of different places and I want to parse all of them in a foreach loop) it doesn't work.
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->$places[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->$places[0]->geometry->location->lng;
}
Solution is changing $places to {$places}[0]
The $places array contains keywords, such as restaurant or store. So the [0] is referring to the first one in the json which is why it's needed.
Why do you have this in the first loop:
json[0]->restaurant[0]
json[0]->$restaurant[0]
But then in the next you have:
json[0]->$places[0]
json[0]->$places[0]
Perhaps you are parsing the JSON incorrectly and it should be:
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->places[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->places[0]->geometry->location->lng;
}
And then in the first loop, you should do a similar edit to get rid of $restaurant[0]:
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->restaurant[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->restaurant[0]->geometry->location->lng;
}
Then again, unclear on what value $places has when you loop via foreach ($this->placesCachingTypes as $places) {. It does’t make sense what you would be looping through with the value of $places. And perhaps assigning that $places in the loop object of $json_decoded->json[0]-> is the source of your issues? Need more info from you to confirm this.

Accessing an array in an object

If i knew the correct terms to search these would be easy to google this but im not sure on the terminology.
I have an API that returns a big object. There is one particular one i access via:
$bug->fields->customfield_10205[0]->name;
//result is johndoe#gmail.com
There is numerous values and i can access them by changing it from 0 to 1 and so on
But i want to loop through the array (maybe thats not the correct term) and get all the emails in there and add it to a string like this:
implode(',', $array);
//This is private code so not worried too much about escaping
Would have thought i just do something like:
echo implode(',', $bug->fields->customfield_10205->name);
Also tried
echo implode(',', $bug->fields->customfield_10205);
And
echo implode(',', $bug->fields->customfield_10205[]->name);
The output im looking for is:
'johndoe#gmail.com,marydoe#gmail.com,patdoe#gmail.com'
Where am i going wrong and i apologize in advance for the silly question, this is probably so newbie
You need an iteration, such as
# an array to store all the name attribute
$names = array();
foreach ($bug->fields->customfield_10205 as $idx=>$obj)
{
$names[] = $obj->name;
}
# then format it to whatever format your like
$str_names = implode(',', $names);
PS: You should look for attribute email instead of name, however, I just follow your code
use this code ,and loop through the array.
$arr = array();
for($i = 0; $i < count($bug->fields->customfield_10205); $i++)
{
$arr[] = $bug->fields->customfield_10205[$i]->name;
}
$arr = implode(','$arr);
This is not possible in PHP without using an additional loop and a temporary list:
$names = array();
foreach($bug->fields->customfield_10205 as $v)
{
$names[] = $v->name;
}
implode(',', $names);
You can use array_map function like this
function map($item)
{
return $item->fields->customfield_10205[0]->name;
}
implode(',', array_map("map", $bugs)); // the $bugs is the original array

Display most voted posts

I'm using ThumbsUp V2 Voting Script and i'm trying to display the posts based on the number of votes:
<?php $items = ThumbsUp::items()->orderby('votes_total')->get() ?>
The values are stored in mysql so i thought of:
$display = mysql_query("SELECT * FROM banat");
$items = ThumbsUp::items($display)->orderby('votes_total')->get() ;
But i thik i've definitely done this wrong since it's just displaying an output:
Array
If you get an array, you must loop on it to show the data. You cannot just do an echo on a var that is an array. You should have something like this:
foreach($items as $item)
{
echo $item;
}
Your $items is an array, and I assumed you attempted to
echo $items;
Instead you will need to loop over it:
foreach ($items as $item) {
// View the structure of `$item`
print_r($item);
}
If you only expect $items to hold one thing, then just do:
print_r($items[0]);

Categories