I'm working on a facebook app to retrieve information from the user. The overall goal is to make a "interactive story" about the user. So I want the name, birthday etc. But I also want to know their favorite bands. The problem is that I can display the array with all the info needed. But that is to much. I don't want to know the category or the id, I only want to know the name.
$user_music = $facebook->api('/me/music');
print_r ($user_music);
If I use this code, I get something like this:
Array ( [data] => Array (
[0] => Array ( [category] => Musician/band [name] => Red Hot Chili Peppers [created_time] => 2011-03-21T15:01:57+0000 [id] => 8335563918 )
[1] => Array ( [category] => Musician/band [name] => Train [created_time] => 2011-03-21T15:01:57+0000 [id] => 15313895735 ) )
I only want the bands name, but if I use this code:
$user_music = $facebook->api('/me/music');
$music_name = $user_music["name"];
echo $music_name;
it says it doesn't know "name".
You missed 1 array level. To access "name" you should use:
$user_music["data"][0]["name"]
or to get all names you should iterate
foreach($user_music["data"] as $data) {
echo $data["name"];
}
you should do something like this:
$user_music['data'][0]["name"]
or run $user_music['data'] in a foreach loop
Related
I'm having trouble with putting this question to words so ill just use a simple example, hope the title sortof got my problem across.
I'm creating a blog site where I can create blogposts and people can post comments. This is all saved in JSON except for login details which are saved in MySQL.
Now saving the blogposts go fine but I'm now trying to save comments.
Lets say the blogpost array looks like this:
Array
(
[0] => Array
(
[id] => 0
[title] => first blogpost
[content] => blogpost text
)
[1] => Array
(
[id] => 1
[title] => second blogpost
[content] => blogpost 2 text
)
)
Now someone writes a comment on 'second blogpost', I save it into an array like this(user taken from MySQL):
Array
(
[user] => myusername
[comment] => first post was better!
)
Now I want to merge them like this:
Array
(
[0] => Array
(
[id] => 0
[title] => first blogpost
[content] => blogpost text
)
[1] => Array
(
[id] => 1
[title] => second blogpost
[content] => blogpost 2 text
[comments] => Array
(
[user] => myusername
[comment] => first post was better!
)
)
)
I tried searching for a while and I'd expect this to be somewhere on the site already but I can't find it. I tried a couple variations of array_push and array_merge but it always ended up replacing the relevant blogpost instead of adding onto it.
EDIT: Someone noted the new array can't just float around, I think it's better now.
If you had any related key between posts and comments ( like having post_id in comment array ) that would make more sense to merge/put them.
I assume that's your blogpost
Array
(
[0] => Array
(
[id] => 0
[title] => first blogpost
[content] => blogpost text
)
[1] => Array
(
[id] => 1
[title] => second blogpost
[content] => blogpost 2 text
)
)
And your comments should be like:
Array
(
[user] => myusername
[comment] => first post was better!
[post_id] => 1
)
That way, you would be able to find the matched blogpost.
But, outside of your data structure, here is an example to merge an item into an element of an array of array.
A nested loop example.
foreach($posts as &$post){
foreach($comments as $comment){
if($post['id'] == $comment['post_id']){
$post['comments'][] = $comment;
}
}
}
the key here is sending each reference of the element into loop by &$post and then just manipulate them in loop.
Working with indexed arrays. (Like you already have index names as post_id and a comments index as an empty array)
foreach($comments as $comment){
$posts[$comment['post_id']]['comments'][] = $comment;
}
When the blogpost is updated, I assume you can get the id of that blogpost.
Then you can check if your data structure already has a key "comments". If it does not, add the key and create an array containing the comment and the user as the first array.
If it already exists, add a new array with the user and the comment so that there can be multiple comments for each blogpost.
For example using array_map:
$blogPosts = array_map(function ($blogPost) use ($blogPostId, $comment) {
if ($blogPost["id"] === $blogPostId) {
isset($blogPost["comments"]) ? $blogPost["comments"][] = $comment : $blogPost["comments"] = [$comment];
return $blogPost;
}
return $blogPost;
}, $blogPosts);
Php demo
So I fixed it after a bit of thinking
This is the final structure:
Array
(
[0] => Array
(
[id] => 0
[title] => 1st post
[content] => 1st post works!
[date] => 21-01-2019
[comments] => Array
(
[0] => Array
(
[user] => Me
[comment] => hey 1
[date] => 12:02 21-01-2019
)
[1] => Array
(
[user] => Me
[comment] => hey 2
[date] => 12:03 21-01-2019
)
)
)
)
I added a timestamp because of a suggestion here. It's also a simplified version of what I actually use, I tried adding many more comments and on multiple posts which both work.
This is the code, I should mention the ID is in the URL and it's saved as JSON:
$filename = file.json;
$currentArray = json_decode(file_get_contents($filename), true);
$comment = $_POST['comment'];
$username = $_SESSION['username'];
$date = date("H:i d-m-Y");
$id = $_GET['id'];
Pretty straightforward so far, here is how the array is created:
$currentArray[$id]["comments"][] = array (
'user' => $username,
'comment' => $comment,
'date' => $date
);
[$id] saves it to the correct post, ["comments"] saves it to the comments key(or creates it) and the last [] gives every comment a different index inside the ["comments"].
$newJSON = json_encode($currentArray, JSON_PRETTY_PRINT);
file_put_contents($filename, $newJSON);
And lastly encoding it and saving it to JSON.
Hope this helps someone.
PHP / FACEBOOK'S FQL
Thank you for even reading this.
I'm having some serious inception issues, dream within a dream style.
I'm doing a multiquery to get the last 3 places a friend visited. I need to show [timestamp] from the location_post table and then [name] of the place from the page table. Hence the multiquery.
now, i get all the values when i check with print_r. However, when I try to echo it, I'm having serious issues getting into the array.
$query = array(
"theVisit"=>"SELECT page_id, timestamp
FROM location_post
WHERE author_uid=XXXXXXXX LIMIT 3",
"thePlace"=>"SELECT name
FROM page
WHERE page_id IN (SELECT page_id FROM #theVisit)
LIMIT 3"
);
$fql_url = $facebook->api(array(
'method' => 'fql.multiquery',
'queries' => $query
));
So far so good. Now I try to get into the array.
echo $fql_url[0]["name"]["fql_result_set"];
This prints just this: t
(just the letter t)
same goes for doing this:
echo $fql_url[0]["name"][0];
// Prints: t
I can't get my head around it. i've tried thousands of variations to get to the data but just can't get to it.
the fql_result_set seems like the obvious villain.
$fql_url[0]["name"]["theVisit"][0]["page_id"] etc, but it just kills everything that happens in the code after that.
below is the array I get from print_r
Array (
[0] => Array (
[name] => theVisit [fql_result_set] => Array (
[0] => Array (
[page_id] => 6205957466
[timestamp] => 1349138499
)
)
)
[1] => Array (
[name] => thePlace [fql_result_set] => Array (
[0] => Array (
[name] => Best Buy Theater
)
)
)
)
Well I was a bit retarded.
[fql_result_set] is obviously not nested inside ["theVisit"], which I stupidly thought.
I realized this and can easily echo what I need like this
echo $fql_url[0]["fql_result_set"][0]["name"];
this prints the correct page_id (6205957466)
Let me be up front: I'm a PHP hack. There's probably some stupid mistakes in here. Please point them out if you see them.
What I'm trying to do: I'm creating a page for a restaurant that would like their Yelp reviews displayed. I'm using the Yelp Phone API to grab the reviews for the specific business. Please view the sample response on the Yelp API documentation located here: http://www.yelp.com/developers/documentation/phone_api#sampleResponse
What I've done:
Successfully connected to the API and returned a response
echoed values from the response array in a foreach loop.
If you view the documentation, you can see there are a few levels of the response. I can easily print, echo, whatever values from the second tier, but what I'm really after is all nested in the "reviews" section of the response. I'm having trouble figuring out how to echo the values within the reviews section (eg user_name, review_excerpt etc).
My Code:
$yelpstring = file_get_contents("http://api.yelp.com/phone_search?phone=[redactedphonenumber]&ywsid=[redactedapikey]", true);
$obj = json_decode($yelpstring);
foreach($obj->businesses as $key => $business)
{
$reviews = $business->reviews;
//print_r($reviews);
echo $reviews['user_name'];
}
If I echo $reviews, I just get the word "Array". If I print_r($reviews), I get an expected list of keys and values. If I try to echo a specific value from the array(echo $reviews['user_name'], I get nothing. Any light shed on what I'm doing wrong would be greatly appreciated. I'm sure I'm missing something simple. Thank you for your time!
Edit: print_r($reviews) output:
Array ( [0] => stdClass Object ( [rating_img_url_small] => http://media4.px.yelpcdn.com/static/201012164278297776/img/ico/stars/stars_small_2.png [user_photo_url_small] => http://media2.px.yelpcdn.com/static/201012162819681786/img/gfx/blank_user_extra_small.gif [rating_img_url] => http://media4.px.yelpcdn.com/static/201012163489049252/img/ico/stars/stars_2.png [rating] => 2 [user_url] => http://www.yelp.com/user_details?userid=vZbcPrYPSMFIDIfTub5H1g [url] => http://www.yelp.com/biz/jelly-cafe-denver#hrid:u9ckRV6tKApe6Bu93M93CA [mobile_uri] => http://m.yelp.com/biz/5G2X2q9p7QFdm-LbyutltQ?srid=u9ckRV6tKApe6Bu93M93CA [text_excerpt] => I wanted to like this place. It's got the contemporary name and it's full of hipsters. The place looked clean and the style was fun and cute. I felt like... [user_photo_url] => http://media3.px.yelpcdn.com/static/201012161186834854/img/gfx/blank_user_small.gif [date] => 2011-09-07 [user_name] => boycott p. [id] => u9ckRV6tKApe6Bu93M93CA ) [1] => stdClass Object ( [rating_img_url_small] => http://media4.px.yelpcdn.com/static/201012164278297776/img/ico/stars/stars_small_2.png [user_photo_url_small] => http://media1.px.yelpcdn.com/upthumb/MWu84G5QtmBmT9GoqjT_kg/ss [rating_img_url] => http://media4.px.yelpcdn.com/static/201012163489049252/img/ico/stars/stars_2.png [rating] => 2 [user_url] => http://www.yelp.com/user_details?userid=izF2cGrmqt-u_Z2tDZ8dbg [url] => http://www.yelp.com/biz/jelly-cafe-denver#hrid:OYLeeCMgnpZkk1c9LWu97g [mobile_uri] => http://m.yelp.com/biz/5G2X2q9p7QFdm-LbyutltQ?srid=OYLeeCMgnpZkk1c9LWu97g [text_excerpt] => Food is decent and overpriced, but service is a joke. Your food will take a minimum of 20 minutes, for the basic breakfast. Then when your food does come... [user_photo_url] => http://media1.px.yelpcdn.com/upthumb/MWu84G5QtmBmT9GoqjT_kg/ms [date] => 2011-09-06 [user_name] => April H. [id] => OYLeeCMgnpZkk1c9LWu97g ) [2] => stdClass Object ( [rating_img_url_small] => http://media2.px.yelpcdn.com/static/20101216418129184/img/ico/stars/stars_small_4.png [user_photo_url_small] => http://media1.px.yelpcdn.com/upthumb/3euzdGdLZRFxImY68MSg7w/ss [rating_img_url] => http://media2.px.yelpcdn.com/static/201012164084228337/img/ico/stars/stars_4.png [rating] => 4 [user_url] => http://www.yelp.com/user_details?userid=bHR9UU4vtx2QKZD44O0E5g [url] => http://www.yelp.com/biz/jelly-cafe-denver#hrid:njvNAzfSII3PxXyUymLZ1w [mobile_uri] => http://m.yelp.com/biz/5G2X2q9p7QFdm-LbyutltQ?srid=njvNAzfSII3PxXyUymLZ1w [text_excerpt] => Stopped here for breakfast on a friday morning. We were seated immediately and had a really friendly waitress. I ordered a side order of the Chai french... [user_photo_url] => http://media1.px.yelpcdn.com/upthumb/3euzdGdLZRFxImY68MSg7w/ms [date] => 2011-09-05 [user_name] => Diane F. [id] => njvNAzfSII3PxXyUymLZ1w ) )
Based on the output of print_r you can't reference $reviews['user_name'];
Note that $reviews is an Array of objects. So to access user_name you need to use
echo $reviews[0]->user_name;
And if you have more than one item in the array, you will need a loop like
for ($i = 0; $i<count($reviews); $i++) {
echo $reviews[$i]->user_name;
}
I hope this helps.
$reviews is an array of review objects. You'll need to loop over it to get to the data you're after.
I have a little problem with array. Im using codeigniter. What i want to do, is something like that:
$studentSchool = $students->schoolId;
echo $shools->id[$studentSchool]->schoolName;
Its in foreach $students loop, and array with schools looks like that:
Array ( [0] => stdClass Object ( [id] => 1 [schoolName] => Akademia Ekonomiczna ) [1] => stdClass Object ( [id] => 2 [schoolName] => Politechnika ) )
Those are my first steps in php and codeigniter, so please have mercy :)
If $schools is the array, you have to access the it as an array. It won't have an id property;
You should build your $schools array such that the index of element corresponds to the ID of the school. I.e. you should have:
Array (
[1] => stdClass Object ( [id] => 1 [schoolName] => ... )
[2] => stdClass Object ( [id] => 2 [schoolName] => ... )
)
Then you can do:
echo $schools[$studentSchool]->schoolName;
Or, if the schools are sorted by ID and the IDs are continuous, you can also do:
echo $schools[$studentSchool - 1]->schoolName;
Otherwise you have to loop over the array to find the right entry for the given ID which is expensive and unnecessary.
Learn more about arrays.
Is this what you're looking for?
foreach ($students as $student):
// Prints the School name for this student
echo $student->schoolName;
endforeach;
Or maybe this?:
// Prints the School name for the first student
echo $students[0]->schoolName
EDIT: This is what you want?
$studentSchool = $students->schoolId;
echo $shools[$studentSchool]->schoolName;
I've hit a bit of a problem, I'm currently working on a custom CMS that allows the user to change the websites title, description, keywords and footer, as well as various other settings, which are all kept in one mysql table called site_settings which has two columns
setting and content, the setting column holds the settings name, for example title, and the content holds the information such as "welcome to my website", these are loaded into the site by various queries which works great, the trouble im having is I want to load the information into the form fields in the CMS, which I was hoping to do with the following query
$query = mysql_query("SELECT `setting`, `content` FROM `site_settings`");
and then create an array with the information using:
$content = mysql_fetch_array($query);
but the only way to get the information is to make a while statement that cycles through every row until it reaches the end, but what i want to be able to do is use the setting column in my table as the main identifier for retrieving the content
for example at the moment with the while array my arrays look like this:
Array ( [0] => title [1] => title [2] => title [3] => title )
Array ( [0] => keywords [1] => keywords [2] => keywords [3] => keywords )
Array ( [0] => description [1] => description [2] => description [3] => description )
Array ( [0] => footnote [1] => footnote [2] => footnote [3] => footnote )
Array ( [0] => notice_state [1] => notice_state [2] => 1 [3] => 1 )
Array ( [0] => maintenance_state [1] => maintenance_state [2] => 1 [3] => 1 )
Array ( [0] => notice_message [1] => notice_message [2] => notice [3] => notice )
Array ( [0] => maintenance_message [1] => maintenance_message [2] => maintenance [3] => maintenance )
Array ( [0] => about_us [1] => about_us [2] => about us [3] => about us )
Array ( [0] => article_shorten_length [1] => article_shorten_length [2] => 80 [3] => 80 )
so id have to cycle through them all to retrieve all the information, with the following statement:
while($content = mysql_fetch_array($query)) {
echo $content['content'];
}
but what I'm looking to do is put them all into one array with 1 or a few mysql statements like so
Array (
title -> 'welcome to my website',
description -> 'this is my website',
)
etc...
and just echo in the information by calling the setting column from my array without using a while statement and without a separate mysql query for each row like:
$content['title'];
$content['description'];
Is there a way to do this?
Use a loop with mysql_fetch_row:
while ($row = mysql_fetch_row($query))
{
$content[$row[0]] = $row[1];
}
This avoids reading the whole result set into an array that you then discard. It might be more efficient, therefore.
I am really unsure as to what exactly you want. But if I get your question properly, are you looking for the below:
while($content=mysql_fetch_array($query))
$finalResultObj[$content['setting'] ] = $content['content'];
After this, you have an associative array, and (if I have understood your question properly) you would be able to use it like $finalResultObj['setting'] to get the relevant content.
Are you sure, this is what you want?