PHP JSON data foreach problem - php

I want to make a PHP JSON data foreach, but I met some problem. First: I can not get the properties part. Second it alawys show wrong in line: echo '<div class="image">...
Fatal error: Cannot use object of type stdClass as array in ...
This is the json data:
[
{
"post_id": "504464716_189878284371815",
"message": "\"Happy Birthday to You\" \"Happy Birthday to Mama\"",
"attachment": {
"media": [
{
"href": "http:\/\/www.facebook.com\/photo.php?fbid=493710409716&set=a.453260184716.254996.504464716",
"alt": "",
"type": "photo",
"src": "http:\/\/photos-f.ak.fbcdn.net\/hphotos-ak-snc4\/hs049.snc4\/34793_493710409716_504464716_5821684_2056840_s.jpg",
"photo": {
"aid": "2166659457206182932",
"pid": "2166659457211749620",
"owner": 504464716,
"index": 24,
"width": 225,
"height": 225
}
}
],
"name": "Wall Photos",
"href": "http:\/\/www.facebook.com\/album.php?aid=254996&id=504464716",
"caption": "\"Happy Birthday to You\" \"Happy Birthday to Mama\"",
"description": "",
"properties": [
{
"name": "By",
"text": "Suman Acharya",
"href": "http:\/\/www.facebook.com\/profile.php?id=504464716"
}
],
"icon": "http:\/\/static.ak.fbcdn.net\/rsrc.php\/yD\/r\/aS8ecmYRys0.gif",
"fb_object_type": "album",
"fb_object_id": "2166659457206182932"
},
"action_links": null,
"privacy": {
"value": ""
}
},
...
]
Here is my php code:
foreach ($data as $result) {
echo '<div class="title">'.htmlspecialchars($result->message).'<br />'.htmlspecialchars($result->description).'<br />'.htmlspecialchars($result->caption).'<br />';
if(!empty($result->attachment->properties[0]->text)){
foreach ($result->attachment->properties[0] as $properties) {
echo htmlspecialchars($properties->name).'<br />'.htmlspecialchars($properties->text).'</div>';
}
}
if(!empty($result->attachment->media)){
echo '<div class="image"><img src="'.htmlspecialchars($result->attachment->media[0]->src).'" /><br>'.htmlspecialchars($result->attachment->media[0]->type).'</div>';
}
}

If i were you i would just force the decoding to an assoc array by true as the second arg to json_decode. If you cant or dont want to do that then try accessing it like this:
$result->attachment->media->{0}->href

Use json_decode($the_data, true); instead of json_decode($the_data); that way it will return you an associative array instead of a StdClass.

Related

How to replace JSON key without losing its value and position using PHP

This is the JSON
{
"table-name": "Kiwi",
"created-on": "November 20, 2021",
"columns": {
"Info": {
"type": "longtext",
"extra": ""
},
"Status": {
"type": "droplist",
"extra": ""
},
"Task": {
"type": "text",
"extra": ""
}
},
"data": [
{
"Name": "Team Reports",
"Info": "Submitting marketing materials reports",
"Status": "Completed"
},
{
"Name": "Fabia HR",
"Info": "Brian asking for a report",
"Status": "Pending"
},
{
"Name": "Fabia",
"Info": "Meeting with CEO #cafe 9:00",
"Status": "Cancelled"
}
]
}
And I was trying to achieve to rename the "Info" into "Description" without losing its value and array position. I'm not very familiar with array_replace , that seems my code is not working. Please share some codes, it will be much appreciated.
Here my PHP code I tried
<?PHP
$jsn = file_get_contents('./test.json');
$arr = json_decode($jsn, true);
$newArray= [];
foreach($arr['data'] as $row){
$row['Description'] = $row['Info'];
array_push($newArray, $row);
}
//print_r($newArray);
array_replace($arr['data'],$newArray);
echo json_encode($arr, JSON_PRETTY_PRINT);
Thank you so much for your attention and advance help. It will really gonna save me some time. Noob here and I'm still learning things about PHP and JSON

How to display company name "only" on friends work history (facebook api)

I have been getting my facebook friends work history. But the result is an array whose content is as follows :
{
"id": "xxx",
"friends": {
"data": [
{
"name": "Indiarto Priadi",
"work": [
{
"employer": {
"id": "111178415566505",
"name": "Liputan 6 SCTV"
}
},
{
"employer": {
"id": "107900732566334",
"name": "SCTV"
}
}
],
"id": "502163984"
},
{
"name": "Agustin Kertawijaya",
"work": [
{
"employer": {
"id": "138215336225242",
"name": "Trader Corporation (Canada)"
},
"location": {
"id": "110941395597405",
"name": "Toronto, Ontario"
},
"position": {
"id": "168673399850791",
"name": "Desktop operator <Pre press>"
},
"start_date": "2006-06-01",
"end_date": "2008-06-01"
},
{
"employer": {
"id": "114464911939560",
"name": "Merrill Corporation Canada"
},
"location": {
"id": "110941395597405",
"name": "Toronto, Ontario"
},
"position": {
"id": "190075304347365",
"name": "Financial Print Project Manager"
},
"start_date": "2006-06-01",
"end_date": "2011-10-01"
}
],
"id": "511990261"
}
],
"paging": {
"next": "https://graph.facebook.com/1065251285/friends?limit=2&fields=name,work&offset=2&__after_id=511990261"
}
}
}
Now i want to display "only" the employer name on my page, but i can't find the way to do that.
Here is my code :
$userFriends = $facebook->api('/'.$userId.'/friends');
for($i=0;$i<=3;$i++){ //retrieved friends (max 4 persons)
$value=$userFriends["data"][$i];
echo "<div id='$value[id]'>";
$profile = $facebook->api("/".$value["id"]);
$friendsWork = $facebook->api("/".$value["id"]."?fields=work");
echo "<strong>".$profile["name"]."<br></strong>";
echo " <img src='https://graph.facebook.com/".$value["id"]."/picture'><br>";
echo "Username : ".$profile["username"]."<br>";
echo "Local : ".$profile["locale"]."<br>";
echo "Birthdate : ".$profile["birthday"]."<br>";
print_r($friendsWork); // <--- the result is an array
echo "<hr>";
echo "</div>";
}
Does anyone know how to display the company(employer) name only?
any answers would be greatly appreciated. Thank You
Here you go, nothing fancy, I just did what I said in my comment
$json = '{
"id": "xxx",
"friends": {
"data": [
{
"name": "Indiarto Priadi",
"work": [
{
"employer": {
"id": "111178415566505",
"name": "Liputan 6 SCTV"
}
},
{
"employer": {
"id": "107900732566334",
"name": "SCTV"
}
}
],
"id": "502163984"
},
{
"name": "Agustin Kertawijaya",
"work": [
{
"employer": {
"id": "138215336225242",
"name": "Trader Corporation (Canada)"
},
"location": {
"id": "110941395597405",
"name": "Toronto, Ontario"
},
"position": {
"id": "168673399850791",
"name": "Desktop operator <Pre press>"
},
"start_date": "2006-06-01",
"end_date": "2008-06-01"
},
{
"employer": {
"id": "114464911939560",
"name": "Merrill Corporation Canada"
},
"location": {
"id": "110941395597405",
"name": "Toronto, Ontario"
},
"position": {
"id": "190075304347365",
"name": "Financial Print Project Manager"
},
"start_date": "2006-06-01",
"end_date": "2011-10-01"
}
],
"id": "511990261"
}
],
"paging": {
"next": "https://graph.facebook.com/1065251285/friends?limit=2&fields=name,work&offset=2&__after_id=511990261"
}}}'; // remember the last two closing curlys, you left them out of the code block in the OP.
$obj = json_decode($json);
foreach ($obj->friends->data as $friend) {
echo '<h1>' . $friend->name . '</h1>';
foreach ($friend->work as $job) {
echo 'Employee: ' . $job->employer->name . '<br/>';
}
echo '<hr>';
}
Output:
Indiarto Priadi
Employee: Liputan 6 SCTV
Employee: SCTV
--------------------------------------
Agustin Kertawijaya
Employee: Trader Corporation (Canada)
Employee: Merrill Corporation Canada
--------------------------------------
You just have to parse the array you obtained, like this-
$userFriends = $facebook->api('/'.$userId.'/friends?fields=work,name');
foreach($userFriends['data'] as $friend)
{
$friend_name = $friend['name'];
$emp_name=array();
// list of all employers of this friend
if(isset($friend['work']))
{
foreach($friend['work'] as $work)
{
array_push($emp_name, $work['employer']['name']);
}
}
else
{
$emp_name = "N.A.";
}
}

Looping over nested arrays below keys

Ok, so that title might be a little misleading, but I'm not quite sure what i'm describing, so here goes.
I have the following JSON :
{
"lastModified": 1368517749000,
"name": "Requiem Paradisum",
"realm": "Chamber of Aspects",
"battlegroup": "Misery",
"level": 25,
"side": 1,
"achievementPoints": 1710,
"emblem": {
"icon": 126,
"iconColor": "ffdfa55a",
"border": 3,
"borderColor": "ff0f1415",
"backgroundColor": "ff232323"
},
"news": [
{
"type": "itemPurchase",
"character": "Osmoses",
"timestamp": 1368482100000,
"itemId": 91781
},
{
"type": "itemLoot",
"character": "Greenmean",
"timestamp": 1368477900000,
"itemId": 87209
},
{
"type": "itemLoot",
"character": "Greenmean",
"timestamp": 1368475800000,
"itemId": 86880
},
{
"type": "itemPurchase",
"character": "Osmoses",
"timestamp": 1368475380000,
"itemId": 91781
},
{
"type": "itemPurchase",
"character": "Osmoses",
"timestamp": 1368475380000,
"itemId": 91779
},
{
"type": "itemPurchase",
"character": "Osmoses",
"timestamp": 1368475320000,
"itemId": 91779
},
{
"type": "playerAchievement",
"character": "Osmoses",
"timestamp": 1368470700000,
"achievement": {
"id": 6193,
"title": "Level 90",
"points": 10,
"description": "Reach level 90.",
"rewardItems": [
{
"id": 87764,
"name": "Serpent's Heart Firework",
"icon": "inv_misc_missilelarge_green",
"quality": 1,
"itemLevel": 1,
"tooltipParams": {
},
"stats": [
],
"armor": 0
}
],
"icon": "achievement_level_90",
"criteria": [
],
"accountWide": false,
"factionId": 2
}
},
Basically i need to loop over everything in "news" and output it.
What I can't figure out how to parse it correctly :
A : without specifying key numbers and
B : when it gets to a key that then contains further keys and further arrays under those keys i'm at a loss. (E.g. the "player achievement" key)
I appreciate I'm probably being a bit newbie here and could quite possibly be on page 1 of "php for dummies" but i swear I've googled it to death!
See if this approach could fit. Be sure your JSON array is properly formatted though.
$test = the_json_array;
$array = json_decode($test,true);
function recursive($array) {
foreach($array as $key => $value) {
if (!is_array($value)) echo $key.":".$value."<br/>";
else recursive($value);
}
}
recursive($array);
SEE json_decode
Dont forget to give second argument as TRUE otherwise it will return object
and try something like this
$json = 'your json'
$json_array = json_decode($json,true);
$news = $json_array['news'];
foreach($news as $value)
{
print_r($value);
}
I think for your purpose you should have look at array_walk_recursive
function printResult($item, $key)
{
echo "$key holds $item\n";
}
array_walk_recursive($news, 'printResult');
yo need to do json_decode('your-jason', True) it will convert your Json string to Array.
Json_decode for more understanding
if you don't specify TRUE in jason_decode function then it will return php object
Hope answer the question. regards

Foreach empty from json

I have the following url:
https://graph.facebook.com/123456/likes?access_token=__ACCESS_TOKEN__&format=json
which I then do:
$likesList = json_decode(file_get_contents("https://graph.facebook.com/123456/likes?access_token=$access_token&format=json"),true);
which produces e.g.
{
"data": [
{
"name": "yo yo yo",
"category": "Entertainer",
"id": "45640987076",
"created_time": "2012-04-18T16:14:09+0000"
},
{
"name": "Tony Smith",
"category": "Musician/band",
"id": "456456456456",
"created_time": "2012-02-22T06:56:18+0000"
},
{
"name": "Stations",
"category": "Company",
"id": "567657567",
"created_time": "2012-01-30T23:08:39+0000"
}
]
}
and I then want to list e.g. all the names returned so:
foreach ($likesList->data as $element2){
$name = $element2[name];
echo $name;
}
But it's empty?
See this visualization of your data structure.
As you are receiving an array, you need $list["data"] and not $list->data. Also don't forget to quote the array key "name".
foreach ($likesList['data'] as $element2){
$name = $element2['name'];
echo $name;
}
After json_decode with parameter true you will have associative array. You can access to value by string key. Like in example above.

imploding array_keys from Facebook JSON data

Need some help with the sample code provided the facebook. I can't get it to return a series of IDs that I need to run a sql query against.
$friends = '{
"data": [
{
"name": "Paul",
"id": "12000"
},
{
"name": "Bonnie",
"id": "120310"
},
{
"name": "Melissa",
"id": "120944"
},
{
"name": "Simon",
"id": "125930"
},
{
"name": "Anthony",
"id": "120605"
},
{
"name": "David",
"id": "120733"
}
]
}';
$obj = json_decode($friends);
print $obj->{'data'}[0]->{'name'};
I can return the "Paul"
what I want is to return all the id's using implode(array_keys($obj),",")
I am only getting data to return.
What I'd like to do is retrieve all the IDs separated by a comma.
Thanks!
Try implode-ing on the data key with array_map:
function get_id($o) {
return $o->id;
}
implode(array_map('get_id', $obj->data),",")

Categories