Printing elements of StdObject Array PHP - php

This is a tricky one (for me). I have an Array of data returned from a Twitter API call in an Array. I'm iterating the "Top 10 Trending" however cannot print the individual elements i.e. name, Below is the code I am using to get as far as I can:
$twitter = new TwitterOAuth($consumerKey,$consumerSecret,$oAuthToken,$oAuthSecret);
$locale = $twitter->get('https://api.twitter.com/1.1/trends/place.json?id=560472');
foreach($locale as $local)
{
print_r($local->trends);
}
This results in the below:
However I cannot access the individual elements through the Array at the top. Any suggestions?
Thank you in advance, Niall

$tweets = $local->trends;
echo $tweets[1]->name;
Or you can use foreach :
foreach ($local->trends as $trend)
{
echo $trend->name;
}

Related

I want a query result using codeigniter

i have an array result. i want to print 2 rows(product data) in first page.
next 2 rows in second page and so on. if anybody knows this,please help me to solve it
my array
$data['product_list']
foreach($data['product_list'] as $dat)
{
echo $dat->prd_id;
echo $dat->prd_name;
}
You are doing a foreach loop on an associative array and then trying to access the the contents as objects by using ->. I can only given assumption of what you might be doing. If your array is already populated with a name and id like you have described in your foreach loop this is how you would access the contents in the loop:
foreach($data['product_list'] as $dat)
{
echo $dat['prd_id'];
echo $dat['prd_name'];
}
That is how you would print out the contents providing you had the data stored in your array like so:
$data['product_list'][0] = array('prd_id'=>'id0','prd_name'=>'name0');
$data['product_list'][1] = array('prd_id'=>'id1','prd_name'=>'name1');
$data['product_list'][2] = array('prd_id'=>'id2','prd_name'=>'name2');
Better you try with array_slice();
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>

echo parts of json returned in php

my returned json looks like this http://pastebin.com/Nbr161s3
I want to echo
body->airTicketListResponse->routings->mainAirlineName
body->airTicketListResponse->routings->adultBasePrice
body->airTicketListResponse->routings->trips->segments->departureAirportCode
body->airTicketListResponse->routings->trips->segments->departureTime //only the time here
body->airTicketListResponse->routings->trips->segments->duration
for each routings.
How do I do this? Here is what I have but I am lost and I know it is way off.
$result = data returned here http://pastebin.com/Nbr161s3
$airTicketListResponse = $result->body->airTicketListResponse;
$routings = $result->body->airTicketListResponse->routings;
$trips = $result->body->airTicketListResponse->routings->trips;
$segments = $result->body->airTicketListResponse->routings->trips->segments;
foreach($airTicketListResponse as $item){
$i=0;
$i<count($routings);
echo '<span style="font-weight:bold;">Airline - '.$item->routings[i]->mainAirlineName.' Price - '.$item->routings[i]->adultBasePrice.'</span><br />'.$item->routings[i]->trips[i]->segments[i]->departureAirportCode.' '.$item->routings[i]->trips[i]->segments[i]->departureTime.'<br /><br />';
$i++;
}
Please help if you can.
Before working with JSON you should be familiar with working with arrays and objects since JSON is nothing more than that.
It seems you already know these two concepts
To access an object property in PHP you use obj->property
To access a value of an array you specify the index inside brackets array[0]
With JSON you just have to keep in mind that some of your object properties will be arrays.
Now, since your data comes in a multi-level three-like structure you should also be familiar with traversing arrays, PHP offers an implementation of a foreach loop that is ideal for traversing dynamically generated arrays
using foreach($array as $index => $var) the $index and $var variables are automatically set to the index and value of each element in the array as they are being traversed, so you don't manually need to keep track of the index (i.e. $i)
Now let's start going through your data:
First we find your routings array
$result = json_decode($data);
$airTicketListResponse = $result->body->airTicketListResponse;
$routings = $airTicketListResponse->routings;
Now we use foreach to loop through every routing and print the needed properties
foreach($routings as $routing){ //$routing will hold the object value in each loop
echo 'Airline '.$routing->mainAirlineName.'<br>';
echo 'Adult Base Price '.$routing->adultBasePrice.'<br>';
}
Getting single properties like the above is pretty straight forward, but for the information of the segments we would first need a nested foreach since we have multiple trips for each routing and then a second nested foreach since each trip has multiple segments
foreach($routings as $routing){ //$routing will hold the object value in each loop
echo 'Airline '.$routing->mainAirlineName.'<br>';
echo 'Adult Base Price '.$routing->adultBasePrice.'<br>';
foreach($routing->trips as $trip){
foreach($trip->segments as $index => $segment){
echo 'Segment '.$index.':<br>'
echo 'Depart From '.$segment->departureAirportCode.'<br>';
echo 'Departure Time '.$segment->departureTime.'<br>';
echo 'Duration '.$segment->duration.'<br>';
}
}
}
And that would be it. I hope my explanation was clear and you got the idea of how to traverse JSON objects
If you feel more comfortable working with an array than with an object to access your data [which might be where you're getting confused here] then you can use json_decode with an additional argument:
$data = json_decode($result, true);
This will leave you with an array ($data) containing all your flight information, you can then var_dump() it and see the hierarchy you're dealing with and loop through it.

Used jsondecode to get mult-dimensional array, how do I access all children elements

So I used JSON to obtain a multidimensional array. What I'm trying to do is for each listing in the main part of the array (not sure what the technical term is) access the part of the array that is below. I would then like to echo each one of these links.
As you can probably see I'm trying to scrape the images. How do I go about doing this? I love to learn so some hints at first would be greatly appreciated. Thanks guys!
[url] => http://imgur.com/0q4G4qP
Json code
<?php
$jsonurl = "http://www.reddit.com/r/pics.json";
$data = file_get_contents($jsonurl);
$array = json_decode($data, true);
echo "<pre>";
print_r($array);
echo "</pre>";
I am not entirely sure how to do this. I referenced the php manual on how to access these types of arrays, but I'm a bit lost. Basically for everyone of those children.
You can do this:
foreach ($multi_d_array['data']['children'] as $item) {
echo $item['data']['url'].'<br/>';
}
Use foreach in loops foreach($data as $d) { echo $d['url'] ;}

Converting XML file elements into a PHP array

I'm trying to convert a Steam group members list XML file into an array by using Php.
The XML file is: http://steamcommunity.com/groups/starhawk/memberslistxml/?xml=1.xml
The elements are the member's steam IDs, such as 76561198000264284
How can I go about doing this?
Edit: So far I've used something like this:
$array = json_decode(json_encode((array)simplexml_load_string($xml)),1);
It outputs the first few elements, not ones specifically
from
This should return the fully accessible array:
$get = file_get_contents('http://steamcommunity.com/groups/starhawk/memberslistxml/?xml=1.xml');
$arr = simplexml_load_string($get);
print_r($arr);
You can now access items like this:
echo $arr->groupID64;
echo $arr->members->steamID64;
Edit:
To parse the streamID, you can do a for loop
$ids = $arr->members->steamID64;
foreach($ids as $id) {
echo $id;
}
you can use below functional code to get your correct answer
<?php
$getfile = file_get_contents('http://steamcommunity.com/groups/starhawk/memberslistxml/?xml=1.xml');
$arr = simplexml_load_string($getfile);
foreach($arr->members->steamID64 as $a => $b) {
echo "<br>".$a,'="',$b,"\"\n";
}
?>
OUTPUT
steamID64="76561198009904532"
steamID64="76561198004808757"
steamID64="76561198000264284"
steamID64="76561198016710420"
steamID64="76561198005429187"
steamID64="76561198030184436"
steamID64="76561197980763372"
steamID64="76561197972363016"
steamID64="76561198045469666"
steamID64="76561198010892015"
steamID64="76561198028438913"
steamID64="76561197967117636"
steamID64="76561197980283206"
steamID64="76561197992198727"
steamID64="76561198018960482"
steamID64="76561198071675315"
steamID64="76561198010447988"
steamID64="76561198025628761"
if you wish to customize you can make it as per your need. let me know if i can help you more..

Domain index checking using Google API

I am trying to build website where a user can enter his website and check his indexed pages in google.
Just like we do by site:domain.com
I am using a google API, here is the link to API (I know it's deprecated)
http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=
when I use a code like
<?php
function getGoogleCount($domain) {
$content = file_get_contents('http://ajax.googleapis.com/ajax/services/' .
'search/web?v=1.0&filter=0&q=site:' . urlencode($domain));
$data = json_decode($content);
return ($data->responseData->cursor->estimatedResultCount);
}
echo getGoogleCount('stackoverflow.com');
?>
good as far as I want to know about the result counts
But the next thing I want is to list all the results on my website. I am unable to grab the results because when we write
$data->responseData->cursor->estimatedResultCount
It goes straight
But when we try to get results. I don't know how to do, just to print the idea
$data->responseData->results->[url & title & content here]
Because here results is an array. and I don't know how can I store info in an array in this case.
Have been searching for a long time but can't find anything related.....
Thanks in advance...
The easiest way is to use:
$data = json_decode($content, true);
That will convert objects to normal associative arrays which are probably easier to handle.
Then you access your values by something like this:
$results = $data['responseData']['results']; //array
$googleCount = $data['responseData']['cursor']['estimatedResultCount'];
Then with the results you can do something like this:
foreach ($results as $result) {
echo $result['title'].' -> '.$result['url'] . '<br />';
}
But of course if you don't like associative arrays and you prefer objects, you could do it also this way:
$data = json_decode($content);
foreach ($data->responseData->results as $result) {
echo $result->title .' -> '.$result->url.'<br />';
}
If you want to check which properties has the $result, just use print_r or var_dump.

Categories