Array of Freebase MIDs and sending multiple queries to freebase

这一生的挚爱 提交于 2019-12-09 22:59:20

问题


I want to loop through the MySQL results which is an array of Freebase MIDs and I want the output to be the names of the Freebase article!

Here's my code:

$query = "SELECT `mid` FROM `items`";
$result = mysql_query($query);
$count = 1;
while ($row = mysql_fetch_array($result)) {
   $mid = $row['mid'];
   $simple_query = array('name'=> null, 'mid'=>$mid);
   $q_array = array('q'.$count=>array('query'=>$simple_query));
   array_push ($query_array, $q_array );
   $count++;
}

$jsonquerystr = json_encode($query_array);
$apiendpoint = "http://api.freebase.com/api/service/mqlread?queries";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$apiendpoint=$jsonquerystr");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonresultstr = curl_exec($ch);
curl_close($ch);
$resultarray = json_decode($jsonresultstr, true); #true:give us the json struct as an array

foreach($resultarray as $name){
    echo "$name<br>";
}

error:

{ "code": "/api/status/error", "messages": [ { "code": "/api/status/error", "message": "'list' object has no attribute 'get'" } ], "status": "500 Internal Error", "transaction_id": "cache;cache04.p01.sjc1:8101;2012-05-14T07:31:39Z;0079" }


回答1:


Your $query_array should just be an associative array of queries by name rather than an array of associative arrays. So instead of this:

$q_array = array('q'.$count=>array('query'=>$simple_query));
array_push ($query_array, $q_array );

..it should look something like this:

$q_array = array('query'=>$simple_query);
$query_array['q'.$count] = $q_array;

However, that code is using the old Freebase API which is about to be deprecated. A better way to do this in the new API would be to structure it all as one query like this:

[{
  "mid": null,
  "name": null,
  "topics:mid|=":[
    "/m/045c7b",
    "/m/0d6lp",
    "/m/021ympy",
    ...
    ]
}]

This lets you pass in an array of MIDs and get back a name for each one. The URL to fetch this from the new API should look something like this:

https://www.googleapis.com/freebase/v1/mqlread/?query=[{...}]



来源:https://stackoverflow.com/questions/10613103/array-of-freebase-mids-and-sending-multiple-queries-to-freebase

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!