【问题标题】:Sort SQL JOIN results in PHP arrays对 PHP 数组中的 SQL JOIN 结果进行排序
【发布时间】:2012-07-11 14:50:15
【问题描述】:

我有 2 个关系表:

table "categories"
id int(11)
title varchar(255)

table "posts"
id int(11)
title varhcar(255)
category_id int(11) // foreign key

如果我选择“类别”表,我想获得一个包含所有类别的 PHP 数组(如“SELECT * 类别”),但包括一个包含所有帖子的内部数组:

Array (
    /* first category */
    [0] = Array (
        [id] => 1
        [title] => "Rock"
        /* all its posts */
        [posts] => Array (
            [0] = Array(
                [id] = 100
                [title] = "Rock post title"
                [category_id] = 1
            )
            [1] = Array(
                [id] = 101
                [title] = "Other rock post title"
                [category_id] = 1
            )
     )
    /* second category */
    [1] = Array (
    )
/* ... */
)

如果我只是进行“加入”查询,我会将所有结果组合在一起,例如:

id     title    id    title               category_id
1      Rock     100   "Rock post title"   1
2      Rock     101   "Other rock post"   1
3      Rock     102   "Final rock post"   1

我不想进行多个查询,因为我认为效率低下。

有没有办法通过一个查询来实现期望的结果?

我知道 CakePHP 设法以这种格式返回关系表结果,所以我希望获得相同的结果。

【问题讨论】:

  • 连接查询很好,你只需要循环遍历结果来创建你想要的数组结构。

标签: php mysql join multidimensional-array


【解决方案1】:

连接应该类似于:

select c.id, c.title, p.id, p.title, p.category_id 
from categories c, posts p
where c.id = p.category_id 
order by c.id, p.id

【讨论】:

    【解决方案2】:

    首先,如果您想要此功能,请考虑使用 ORM 库(例如 CakePHP 和其他框架提供的库),而不是为已经解决的问题编写自己的代码。

    你不能在 SQL 中做“内部数组”,这很丑陋(比如将记录打包到一个字符串列中,然后在 PHP 中将它们解包)。

    但对于一个快速的“n 脏”解决方案,只要您在查询中重命名帖子 ID 和标题(例如,“post_id”)以避免与类别 ID 混淆,只需使用原始连接查询即可。然后遍历结果集并构建您的数组。

    $newArray = array();
    foreach($resultset as $row) {
        if(!array_key_exists($row['category_id'],$newArray)) {
           $newArray[$row['category_id']] = array('id' => $row['category_id'], 'title' => $row['title'], 'posts' => array());
        }
        $newArray[$row['category_id']]['posts'] = array('id' => $row['post_id'], 'title' => $row['post_title'], 'category_id' => $row['category_id']);
    }
    

    我没有在编辑器中编写此代码,因此对于拼写错误,我深表歉意。你明白了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-29
      • 2017-06-14
      • 2011-09-28
      • 2018-08-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-02
      相关资源
      最近更新 更多