Echo element from php array - php

Can someone tell me how I can loop through the below array?
http://pastebin.com/rhaF5Zdi
I've tried with out luck:
$_data = json_decode($_data);
foreach ( $_data as $tweet )
{
echo "{$tweet->text}\n";
}
thanks
ps: im follwoing this php script.
http://mikepultz.com/2013/06/mining-twitter-api-v1-1-streams-from-php-with-oauth/
hers another paste bin on the array. there seems to be multiple arrays happening
http://pastebin.com/dduzhpqY

It looks like you might be creating a PHP stnd object instead of an array
//this will create a php standard object
$objOfData=json_decode($json);
Instead Use the version below: (Notice the the 2nd parameter is TRUE)
$associativeArray=json_decode($json, TRUE);
This will turn the object into an associative array and you can access fields like so:
$id=$associativeArray['id'];
More info here: json_decode

The code in posted link is not JSON, but it is output of print_r() function. PHP has no invert function to print_r(), but on php.net in print_r() documentation's comments you can find some user-made functions which can read it.
For example this one:
http://www.php.net/manual/en/function.print-r.php#93529
I hope it will help. Good Luck :)

Ended up using:
if(array_key_exists('text', $_data)){
echo 'Tweet ID = '.$_data['id_str'];
echo 'Tweet Text = '.$_data['text'];
echo '<br /><br />';
}
cheers

Related

PHP Array inside of an array issue

I'm having some problems getting the data through my PHP loop.
<?php
$url = 'https://www.fibalivestats.com/data/1653309/data.json';
$content = file_get_contents($url);
$json = json_decode($content, true);
?>
<?php
foreach($json['totallds']['sPoints'] as $item); {
echo $item;
}
?>
The error I'm getting is an array to string conversion error. What I'm trying to get is the data from the sPoints array that will give me a Top 5 points scorers for a basketball game.
I'll build a table for this in HTML later but for now, it's not displaying the data at all and I'm getting errors. I feel like I may have confused arrays and strings too. Any thoughts about what I'm doing wrong? JSON file can be found in the $url variable.
Also if it helps, here's the link to where I have gotten the data from and what context the Top 5 is from https://www.fibalivestats.com/u/NSS/1653309/lds.html
Thanks!
Your $item is an array, so you can't just echo it like that. You can, however, echo its columns, for example:
foreach($json['totallds']['sPoints'] as $item) {
echo $item['firstName'] . ' ' . $item['familyName'];
}
Notice the removed semicolon between the foreach () and {.
Well, array to string conversion error means you're trying to echo an array.
If you see the return of the url you are looking at, you can verify that the "sPoints" key returns an array with several objects.
Try to change echo to print_r or var_dump to view entire data or complete your business logic.
Try changing:
echo $item;
to:
var_dump($item);

extract specific data from array in mysql database using php

This is the data that i need to extract like example profile_contact_numbers
so the output will be +639466276715
how can i do it in php code??
any help will do regards
a:2:
{s:23:"profile_contact_numbers";s:13:"+639466276715";s:16:"profile_position";s:7:"Courier";}
I'm not sure 100% this can go into an array but try the unserialize function
$json_resp = {your values};
$array[] = unserialize($json_resp);
To check if it has gone into an array print_r on $array.
Read this link if the code above doesn't work
http://php.net/manual/en/function.unserialize.php
I have managed to fix it
$serialized = array(unserialize('a:2:{s:23:"profile_contact_numbers";s:13:"+639466276715";s:16:"profile_position";s:7:"Courier";}'));
var_dump($serialized);
use code :
$var = preg_split('["]','{s:23:"profile_contact_numbers";s:13:"+639466276715";s:16:"profile_position";s:7:"Courier";}');
echo $var[1].'='.$var[3]; // profile_contact_numbers=+639466276715
echo $var[5].'='.$var[7]; // profile_position=Courier

create an empty object in JSON with PHP?

i have create json from an array but how we can make an empty json
$jsonrows['paymentmethods']['CC']=array()
json_encode($jsonrows['paymentmethods']['CC']=array())
currently output is like this
"CC":[]
what i need is
"CC":{}
please help me with this
Use a class instead of an array:
var_dump(json_encode(new StdClass()));
Try This
$cc['CC'] = new stdClass ;
echo json_encode($jsonrows['paymentmethods']=$cc);
Output is
{"CC":{}}
For code readability, I use $emptyObject = (object)[];
In the context of your example:
$jsonrows['paymentmethods']['CC']=array();
echo json_encode($jsonrows['paymentmethods']);
yields the undesired: {"CC":[]}
$jsonrows['paymentmethods']['CC']=(object)array();
echo json_encode($jsonrows['paymentmethods']);
gives what you want: {"CC":{}}

Access JSON values in PHP

{"coord":{"lon":73.69,"lat":17.8},"sys":{"message":0.109,"country":"IN","sunrise":1393032482,"sunset":1393074559},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}],"base":"cmc stations","main":{"temp":293.999,"temp_min":293.999,"temp_max":293.999,"pressure":962.38,"sea_level":1025.86,"grnd_level":962.38,"humidity":78},"wind":{"speed":1.15,"deg":275.503},"clouds":{"all":0},"dt":1393077388,"id":1264491,"name":"Mahabaleshwar","cod":200}
I am trying to fetch description from the weather from the json above but getting errors in php. I have tried the below php code:
$jsonDecode = json_decode($contents, true);
$result=array();
foreach($jsonDecode as $data)
{
foreach($data{'weather'} as $data2)
{
echo $data2{'description'};
}
}
Any help is appreciated. I am new in using json.
You have to use square brackets ([]) for accessing array elements, not curly ones ({}).
Thus, your code should be changed to reflect these changes:
foreach($data['weather'] as $data2)
{
echo $data2['description'];
}
Also, your outer foreach loop will cause your code to do something completely different than you intend, you should just do this:
foreach($jsonDecode['weather'] as $data2)
{
echo $data2['description'];
}
Your $jsonDecode seems to be an array, so this should work-
foreach($jsonDecode['weather'] as $data)
{
echo $data['description'];
}
You can access data directly with scopes
$json = '{"coord":{"lon":73.69,"lat":17.8},"sys":{"message":0.109,"country":"IN","sunrise":1393032482,"sunset":1393074559},"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}],"base":"cmc stations","main":{"temp":293.999,"temp_min":293.999,"temp_max":293.999,"pressure":962.38,"sea_level":1025.86,"grnd_level":962.38,"humidity":78},"wind":{"speed":1.15,"deg":275.503},"clouds":{"all":0},"dt":1393077388,"id":1264491,"name":"Mahabaleshwar","cod":200}';
$jsonDecode = json_decode($json, true);
echo $jsonDecode['weather'][0]['description'];
//output Sky is Clear
As you can see wheater` is surrounded with scopes so that means it is another array. You can loop throw that array if you have more than one result
foreach($jsonDecode['weather'] as $weather)
{
echo $weather['description'];
}
Live demo
If the result of decode is an array, use:
$data['weather']
If the result is an object, use:
$data->weather
you have to access "weather" with "[]" operator
like this,
$data["weather"]
There is several things worth answering in your question:
Q: What's the difference between json_decode($data) and json_decode($data, true)?
A: The former converts JSON object to a PHP object, the latter creates an associative array: http://uk1.php.net/json_decode
In either case, there is no point on iterating over the result. You probably want to access just the 'weather' field:
$o = json_decode($data) => use $weather = $o->weather
$a = json_decode($data, true) => use $weather = $a['weather']
Once you have the 'weather' field, look carefully what it is:
"weather":[{"id":800,"main":"Clear","description":"Sky is Clear","icon":"01n"}]
It's an array, containing a single object. That means you will either need to iterate over it, or use $clearSky = $weather[0]. In this case, it does not matter which approach of json_decode did you choose => JSON array is always decoded to a PHP (numeric indexed) array.
But, once you get $clearSky, you are accessing the object and it again matters, which approach you chose - use arrow or brackets, similarly to the first step.
So, the correct way to get for exaple the weather description would be either of these:
json_decode($data)->weather[0]->description
json_decode($data, true)['weather'][0]['description']
Note: In the latter case, dereferencing result of the function call is supported only in PHP 5.4 or newer. In PHP 5.3 or older, you have to create a variable.
Note: I also encourage you to always check if the expected fields are actually set in the result, using isset. Otherwise you will try to access undefined field, which raises an error.

How to decode the following code in Json?

I'm trying to decode the following JSON using php json_decode function.
[{"total_count":17}]
I think the square brackets in output is preventing it. How do I get around that? I can't control the output because it is coming from Facebook FQL query:
https://api.facebook.com/method/fql.query?format=json&query=SELECT%20total_count%20FROM%20link_stat%20WHERE%20url=%22http://www.apple.com%22
PHP's json_decode returns an instance of stdClass by default.
For you, it's probably easier to deal with array. You can force PHP to return arrays, as a second parameter to json_decode:
$var = json_decode('[{"total_count":17}]', true);
After that, you can access the variable as $result[0]['total_count']
See this JS fiddle for an example of how to read it:
http://jsfiddle.net/8V4qP/1
It's basically the same code for PHP, except you need to pass true as your second argument to json_decode to tell php you want to use it as associative arrays instead of actual objects:
<?php
$result = json_decode('[{"total_count":17}]', true);
print $result[0]['total_count'];
?>
if you don't pass true, you would have to access it like this: $result[0]->total_count because it is an array containing an object, not an array containing an array.
$json = "[{\"total_count\":17}]";
$arr = Jason_decode($json);
foreach ($arr as $obj) {
echo $obj->total_count . "<br>";
}
Or use json_decode($json, true) if you want associative arrays instead of objects.

Categories