PHP:合并两个MySql数组结果

时间:2014-06-08 19:33:31

标签: php mysql

i fetch id和类别表中的名称,如下所示:

  |id|name| tag |desc|order|status|
  |1 |test| NULL|NULL|  1  |   1  |


  $i = 0;
  $allcats = Access::FETCH("SELECT * FROM " . CATS . "");
     $cats = array();
  foreach($allcats AS $row2){                                               
     $cats[$i] = array("name" => $row2['name'], "id" => $row2['id']);
  $i++;                                             
  }

我获取每条新闻的类别ID:

|id|catid|storyid|
|1 |  1  |   5   |

$groupcats = Access::FETCH("SELECT * FROM " . GROUPCATS . " WHERE  storyid = ?", $row['postid']);

现在,我需要为storyid打印猫的名字。我,e:我需要为故事ID 5打印test(catname)。

我该如何打印?

2 个答案:

答案 0 :(得分:3)

使用join而不是php更容易处理。像,

$joinedcats = Access::FETCH("SELECT name FROM " . CATS . 
                            " JOIN " . GROUPCATS . " ON catid = id");
foreach($joinedcats as $row) {
     echo $row['name'];
}

请参阅https://dev.mysql.com/doc/refman/5.5/en/join.html

答案 1 :(得分:0)

您可以使用连接为每个故事获取所需的行:

"SELECT * FROM " . GROUPCATS . " LEFT JOIN " . CATS . " USING(categoryid) WHERE  storyid = ?"