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)
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.
STARTING ARRAY
Array
(
[0] => Array
(
[0] => /searchnew.aspx?Make=Toyota&Model=Tundra&Trim=CrewMax+5.7L+V8+6-Spd+AT+SR5&st=Price+asc
[1] => 19
)
)
I have been struggling to break down this array for the past couple days now. I have found a few useful functions to extract the strings I need when a start and end point are defined, however, I can't see that being good for long term use. Basically I'm trying to take the string relative to [0], and extract the strings following "Model=" and "Trim=", in hopes to have array like this:
Array
(
[0] => Array
(
[0] => Tundra ***model***
[1] => CrewMax+5.7L+V8+6-Spd+AT+SR5 ***trim***
[2] => 19
)
)
I'm getting this information fed through an api, so coming up with a dynamic solution is my biggest challenge. I realize this a big question, but is there a better/less hacky way of approaching this problem?
parse_url() will get you the query string and parse_str() parses the variables from that:
$q = parse_url($array[0][0], PHP_URL_QUERY);
parse_str($q, $result);
print_r($result);
Yields:
Array
(
[Make] => Toyota
[Model] => Tundra
[Trim] => CrewMax 5.7L V8 6-Spd AT SR5
[st] => Price asc
)
Now just echo $result['Model'] etc...
Hi i got this array here and i want to put it into mysql database,
here is my array
$v = "Tom: 2000, Bob: 300, Jack: 500"
$x is Array ( [0] => Array ( [0] => Tom [1] => 2000 ) [1] => Array ( [0] => Bob [1] => 300 ) [2] => Array ( [0] => Jack [1] => 500 ) )
and this is my code to put it into database:
$f=explode(",",$v);
for($i=0;$i<sizeof($f);$i++){
$x[$i]=explode(": ",$f[$i]);
$player=$x[$i][0];
$win=$x[$i][1];
$sql = "UPDATE scores SET win=$win WHERE player='$player'";
$result = $conn->query( $sql );
}
but the problem is for loop only puts 'Tom' and '2000' (which are first) into database and nothing happens to other player's row, i think this code should work fine but i cant find what is the problem.
Do the other records exist? I see you're doing an UPDATE and not an INSERT, so maybe the other records mismatch on "player"?
You also might want to use trim() on $player and $win, to remove any whitespace from the explode() output.
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
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?