douju9847 2011-07-13 02:49
浏览 42
已采纳

在mySQL中构造php数据

I've got a data schema like this:

cp
    id    te    su
    1     7     2
    2     7     1
    3     6     8

cl
    id    cp    st
    1     2     5
    2     2     6
    3     1     6

us
   id    na
   ..    ..
   5     Joe
   6     Mike
   7     Tina
   ..    ..

I want to run a php function foo($te) with foo(7) to output data like this from mySQL

[0]
    su: 1
    st_list:
        [0]
            id:6
            na:Mike
[1]
    su: 2
    st_list:
        [0]
            id:5
            na:Joe
        [1]
            id:6
            na:Mike

I want to know how best to do this. Right now I'm able to use JOINs, but the result looks like this

[0]
    su: 1
    st_id:6
    st_na:Mike
[1]
    su: 2
    st_id:5
    st_na:Joe
[3]
    su: 2
    id:6
    na:Mike

The su:2 is repeated... obviously that isn't a problem in this example, the problem is that in the real thing that su represents a lot more data, that i'll be getting through "this" (whatever answer I choose) method.

EDIT: I hope you understand what I'm asking... I know a lot of you guys are way more knowledgable in mySQL and development in general than me, so that's why i'm asking in such a plain (I HAVE THS----> WANT THIS) way, because I think if I asked any more specifically I would end up making assumptions about the way it should run). I want an effecient solution, because this data is being used to populate search results.

Thanks!!!!!!!!!!

  • 写回答

3条回答 默认 最新

  • dongzai0020 2011-07-21 05:53
    关注

    You will need to loop over the results yourself and build the array in the format you want. MySQL can't give you the results in the nested format you want. Here's a rough draft (untested):

    $su = 0;
    $st_list = array();
    $nested = array();
    foreach ($results as $row) {
        if ($su != 0 && $row['su'] != $su) {
            $nested[] = compact('su', 'st_list');
        }
    
        if ($su != $row['su']) {
            $su = $row['su'];
            $st_list = array();
        }
    
        $st_list[] = array(
            'id' => $row['st_id'],
            'na' => $row['st_na'],
        );
    }
    
    $nested[] = compact('su', 'st_list');
    

    Edit: Usually it's best to simply fetch all the results you want using a single SQL query. That is almost always the most efficient way to do it. But if it really matters to you (and this is a performance critical part of your application), the only way to know for sure is benchmark both methods. A lot depends on your database layout, number of rows, SQL indexes, etcetera.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题