在PHP中发生之前引用下一次迭代

时间:2009-06-12 15:46:31

标签: php mysql

我在MySQL中有一个带有“text”,“date_posted”和“user”的表。我目前查询来自user = Andy的所有文本,然后调用这些问题。来自其他用户的所有其他文本字段都是最近问题的答案。

我想要的是将这些答案与最近的问题相关联,其循环类似于“对于每个用户= Andy的文本,找到用户的文本!= Andy直到日期>下一个用户= Andy(问题) “

这看起来非常糟糕,我想知道它是否可以像我概述的那样粗略地完成,或者我是否可以为我存储数据或其他东西节省一些麻烦。

感谢您的任何建议。

编辑:我已经添加了我一直在使用的插入查询。

$url = "http://search.twitter.com/search.json?q=&ands=&phrase=&ors=&nots=RT%2C+%40&tag=andyasks&lang=all&from=amcafee&to=&ref=&near=&within=1000&units=mi&since=&until=&tude%5B%5D=%3F&rpp=50)";
$contents = file_get_contents($url);
$decode = json_decode($contents, true);
foreach($decode['results'] as $current) {
    $query = "INSERT IGNORE INTO andyasks (questions, date, user) VALUES ('$current[text]','$current[created_at]','Andy')";
    mysql_query($query);
}

$url2 = "http://search.twitter.com/search.json?q=&ands=&phrase=&ors=&nots=RT&tag=andyasks&lang=all&from=&to=amcafee&ref=&near=&within=15&units=mi&since=&until=&rpp=50";
$contents2 = file_get_contents($url2);
$decode2 = json_decode($contents2, true);
foreach($decode2['results'] as $current2) {
    $query2 = "INSERT IGNORE INTO andyasks (questions, date, user) VALUES ('$current2[text]','$current2[created_at]','$current2[from_user]')";
    mysql_query($query2);
}

然后在SELECT方面,这是我目前的位置:

    $results = mysql_query("SELECT * FROM andyasks");
$answers = mysql_query("SELECT * FROM andyasks WHERE 'user' != 'Andy'");
while($row = mysql_fetch_array($results))
{
    if ($row['user'] == 'Andy') {
    print(preg_replace($pattern, $replace, "<p>".$row["questions"]."</p>"));
}
}
while($row = mysql_fetch_array($answers))
{
    print(preg_replace('/@amcafee/', '', "<p>".$row["questions"]."</p>"));
}

2 个答案:

答案 0 :(得分:2)

我相信,您可以巧妙地使用JOIN或嵌套SELECTORDER BYLIMIT等来完成您的工作,但是,正如您所做的那样猜测,这将是“非常人为的”,可能很慢。

正如您所怀疑的那样,如果您在表格中添加了一列,那么您可以在SELECT时节省很多麻烦,对于答案,该列具有他们正在回答的问题的主键(可能很容易在INSERT时间获得,因为这是用户等同Alex的最新条目。然后检索会更容易!

如果您可以通过这种方式更改架构,但需要SQL帮助,请评论或编辑您的答案以表明这一点,我将很乐意跟进(同样,如果您愿意,我也很乐意跟进我坚持使用这种模式,需要“非常人为的”SQL - 我只是不知道这两种可能性中的哪一种适用! - 。)。

编辑:由于架构已更改,INSERT可能是(使用form:name表示应绑定的参数):

INSERT IGNORE INTO andyasks
  (questions, date, user, answering)
  SELECT :text, :created_at, :from_user,
    IF(:from_user='Andy', NULL, aa.id)
  FROM andyasks AS aa
  WHERE user='Andy'
  ORDER BY date DESC
  LIMIT 1

即:使用自动递增的INSERT INTO ... SELECT' to do a query-within-insertion, which picks the latest post by Andy. I'm assuming you do also have a primary key id`,这是正常的事情安排。

稍后要获得给定问题的所有答案,您只需选择answering属性等于该问题的id的行。

答案 1 :(得分:0)

如果我理解正确你想要的东西:

$myArr = array("bob","joe","jennifer","mary");
while ($something = next($myArr)) {
   if ($nextone = next($myArr)) {
       //do Something
       prev($myArr)
   }

}

请参阅http://jp2.php.net/next以及有关prev,reset和current

的部分