What are some effective ways to utilize the outcome of a FB FQL multiquery?

I'm having some confusion with Facebook's fql.multiquery feature.

My goal is to fetch all the comments on a specific post and then retrieve the user information for each commenter. While I can easily get the comments, I am facing difficulty in obtaining the user details.

Currently, I am utilizing the code snippet below:

  FB.api({
   method: 'fql.multiquery',
   queries: {
    query1: 'SELECT post_fbid, fromid, text, time FROM comment WHERE post_id="'+postID +'"',
    query2: 'SELECT id, name, url, pic FROM profile WHERE id IN (SELECT fromid FROM #query1)'
   }
  },
  function(response) {
  }
})

Upon using this, I receive the following response:

[
  {
    "name": "query1",
    "fql_result_set": [
      {
        "post_fbid": "xxxxx",
        "fromid": user1id,
        "text": "Here's a comment",
        "time": 1308579931
      },
      {
        "post_fbid": "xxxxx",
        "fromid": user2id,
        "text": "Another comment",
        "time": 1308580031
      }
    ]
  },
  {
    "name": "query2",
    "fql_result_set": [
      {
        "id": user1id,
        "name": "User 1 name",
        "url": "User 1 url",
        "pic": "User 1 pic"
      },
      {
        "id": user2id,
        "name": "User 2 name",
        "url": "User 2 url",
        "pic": "User 2 pic"
      }
    ]
  }
]

The issue I'm facing is how to link these two sets of data. I need to display each comment along with the corresponding user's name. How can I achieve this?

Alternatively, I'm open to suggestions for a more efficient approach to tackle this task.

Answer №1

To align the results, you can iterate through the comments and compare the fromid to an id in the user's response.

Here is an example:

    var commentsArr = response[0].fql_result_set;
    var usersArr = response[1].fql_result_set;    

    //Iterate through the comments
    for(var i = 0, j = commentsArr.length; i<j; i++){

        for(var x = 0, y = usersArr.length; x<y; x++){
             if(commentsArr[i].fromid === usersArr[x].id){
                 //Found a match, this comment is from user usersArr[x]
                 //Process usersArr[x]
                 //Exit the inner loop as we already have a match
                 break;
             }
        }

    }

Answer №2

For those using PHP and requiring a single array of comments for looping purposes, the following function can be quite helpful:

public function getComments($objectID){
    $user = $comment = array();
    $q1 = "/fql?q=".urlencode("SELECT id, fromid, text, time, likes FROM comment WHERE object_id ='$objectID'");
    $res = $this->api($q1);
    $com = $res['data'];

    $q2 = "/fql?q=".urlencode("SELECT uid, name, username, pic_small, current_location FROM user WHERE uid IN (SELECT fromid FROM comment WHERE object_id ='$objectID')");
    $res = $this->api($q2);
    $usr = $res['data']; 

    foreach($usr as $k=>$v){
        $user[$v['uid']] = $v;
    }
    foreach($com as $cmnt){
        $comment[$cmnt['id']] = $cmnt;
        $comment[$cmnt['id']]['user'] = $user[$cmnt['fromid']];
    }
     return $comment;
}

This function will provide a consolidated array of comments, using the commentID as the key:

Array(

[137194739772009_249649] => Array
    (
        [id] => 137194739772009_249649
        [fromid] => 1454592211
        [text] => Brilliant!
        [time] => 1357450854
        [likes] => 1
        [user] => Array
            (
                [uid] => 1454592211
                [name] => Jo Payne
                [username] => jo.payne.127
                [pic_small] => http://profile.ak.fbcdn.net/hprofile-ak-snc6/203035_1454592211_505092710_t.jpg
                [current_location] => Array
                    (
                        [city] => Pascoe Vale
                        [state] => Victoria
                        [country] => Australia
                        [zip] => 
                        [id] => 107340732634422
                        [name] => Pascoe Vale, Victoria, Australia
                    )

            )

    )

[137194739772009_252711] => Array
    (
        [id] => 137194739772009_252711
        [fromid] => 1734247348
        [text] => testing
        [time] => 1357531321
        [likes] => 0
        [user] => Array
            (
                [uid] => 1734247348
                [name] => Andreas Lustig
                [username] => andreaslustigcom
                [pic_small] => http://profile.ak.fbcdn.net/hprofile-ak-snc6/275058_1734247348_2025403101_t.jpg
                [current_location] => Array
                    (
                        [city] => Melbourne
                        [state] => Victoria
                        [country] => Australia
                        [zip] => 
                        [id] => 116190411724975
                        [name] => Melbourne, Victoria, Australia
                    )

            )

    )

)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Warning: Next.js is throwing a hydration error because the server HTML does not include a matching <main> element within a <div>

I have been encountering hydration issues in my next.js application. After extensive troubleshooting, I have found that the culprit might be the higher order component called withAuth.js The error message displayed is: Warning: Expected server HTML to con ...

Using Express.js and Angular for user authentication and session management

In my current project, I am utilizing expressjs and angularjs to create an app. The setup involves expressjs serving a single .html file that houses an angular single-page-application. All routing is handled by angularjs, while expressjs provides web servi ...

Transform a JSON array into an array of objects using typescript

I have a JSON array that I need to convert into an object type array JSON array [ 0:{code: "00125", scheme: "0001", plotNumber: "125", propType: "001", plotType: "001"} 1:{code: "190", scheme: "0001", plotNumber: "NA 190", propType: "001", plotType: "0 ...

Navigating through tables and selecting rows

I am currently facing an issue with my HTML table that consists of 1000 rows and 26 columns. To navigate between rows and make selections, I have implemented a jQuery plugin on the table. The problem lies in the performance of the plugin, even with the la ...

Error in Java code: Node duplication while converting MySQL hierarchy data into JSON format

Utilizing Spring to retrieve a JSON object as a response from a hierarchy structured across two Mysql tables. ------------ ----------------- | Concepts | | Relationships | |----------| |---------------| | id | | relation_id | | ti ...

Unexpected behavior from vuelidate triggered on blur

I have implemented vuelidate for form validation. My goal is to validate user input either when they move to the next input field or click outside of the current one. <div class="form-group col-md-6" :class="{invalid: $v.partner.email.$ ...

The AJAX requests in my project are failing to trigger upon touch events when using the jQuery Plugin

Ensuring that both <script src="hammer.js"></script> and <script src="../jquery.hammer.js-master/jquery.hammer.js"></script> have been correctly included in my header. I have a mouse click-triggered AJAX event for dynamic and depen ...

Incorporating Error Management in Controller and Service: A Step-by-Step Guide

Take a look at the structure of my angular application outlined below: Within my 'firm.html' page, there is a button that triggers the code snippet provided. Controller The controller initiates a Service function. The use of generationInProgre ...

What is the best way to locate and send a message to a particular channel within a server?

I've been working on a Discord bot using Discord.js and I'm currently attempting to create a welcome command. My goal is to send a message to a specific channel within my server. However, due to recent updates in discord.js, I'm having troub ...

"Looking for a datetime picker plugin that works well with Bootstrap

Check out this efficient DateTimePicker example. <head> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script> <link rel="stylesh ...

What could be the reason behind the disappearance of the lines in my table that was created with the help of HTML, CSS, and JavaScript?

When I added the Modal trigger, the table lines changed. I suspect it has to do with the buttons in the table. I'm new to HTML/CSS/JS so this whole experience is quite different for me. Any advice or tips for future projects would be greatly appreciat ...

Selecting a color in Vuetify's color picker triggers the @

I have incorporated the Vuetify color picker into my project for changing the background and text colors of elements. Currently, I am storing the hex color values in Firestore by using the @input="updateColor" attribute on the v-color-picker to t ...

Form validation using JQuery within a Bootstrap 4 modal incorporating tabs is preventing submission

Encountering a challenge with JQuery Validation within a modal that contains tabs. When I'm on the Sign-in Tab and click the Login button, the validation errors display correctly: https://i.sstatic.net/caReK.jpg ISSUE 1 However, on the New Account ...

The value of $parent.$index will consistently be 0 in all cases

I am currently dealing with a nested ng-repeat situation where I am attempting to determine the parent's index. Due to the fact that it is being arranged post-process, the standard ng-repeat="(step_index, step) in flow" method is not working for m ...

Having trouble displaying the desired formatting when mapping through nested JSON in Node ES6

Currently working on a project to build a photo gallery using nested JSON data. My goal is to iterate through the data and create a well-structured JavaScript object or a smaller JSON file that includes only the text and image URL nodes. However, my curren ...

Error in THREE.js: Unable to access property 'lib' from an undefined source (THREE.ShaderUtils.lib["normal"])

I have been working on the challenges provided in the WebGL introductory book by Oreilly. Encountered a runtime error with the following code snippet. After searching online, it seems like I am the only one facing this issue. Could you please assist me in ...

Angular JS: Saving information with a promise

One dilemma I am facing is figuring out where to store data that needs to be accessed in the final callbacks for an http request. In jQuery, I could easily handle this by doing the following: var token = $.get('/some-url', {}, someCallback); tok ...

Extracting the call from REST API in JSON format

Working with a third-party database using a REST API, I encountered an error response (as expected). Here is the code snippet: transaction.commit(function(err) { if (err){ var par = JSON.parse(err); \\ leading to error: SyntaxError: Unexpecte ...

Node.js refusing to acknowledge the get request handler for the homepage of the website

My Node.js server setup is quite simple: const express = require('express'); const app = express(); const http = require("http"); const path = require('path'); const favicon = require('serve-favicon'); // Public fil ...

Unable to locate a React component module that has been published

After successfully publishing a React component to NPM, I encountered an issue when trying to use it in another project - I couldn't find the module! Module not found: Can't resolve 'react-subreddit-posts' in '/Users/kyle.calica/C ...