doubaisui2526 2010-07-13 15:41
浏览 85
已采纳

加入两个以上的mysql表,然后将行操作为分组的多维数组

I'm trying to join multiple myqsl tables and then process resulting arrays using PHP but I'm having problems manipulating my data to get the groupings I'd like.

table.users
+---------------
uid
name

table.profile_values
+-----------------------
fid
uid
category_value

table.profile_fields
+---------------------
fid
category_title

Here is my sql query:

SELECT users.name, profile_fields.category_title, profile_values.category_value FROM profile_values 
    INNER JOIN profile_fields
        ON profile_values.fid=profile_fields.fid
    INNER JOIN users
        ON users.uid=profile_values.uid
    ORDER BY users.name ASC

Using I while loop over fetch_array(), as expected, I get an array for each row number which looks something like:

Array (
    [0] => Array (
            [name] => Bob
            [category_title] => Occupation 
            [category_value] => IT
            ) 
    [1] => Array ( 
            [name] => Bob 
            [category_title] => Previous Experience 
            [category_value] => Very little.
            ) 
    ...
)

The output I'm actually looking to generate is:

Array( 
    [name] => array(
            [category_title 1] => value 1
            [category_title 2] => value 2
            ...
    )
    ....
)

I've spent the vast part of a day looking at various examples and haven't been able to find one that helps me understand the best place to interject and group my data. I've seen examples using GROUP_CONCAT, which is similar to what I want, but I'd like to keep my data in arrays if possible.

Should I be using a nested foreach loops after I have my rows assigned to arrays, using a GROUP BY in my sql statement, or a combination of both?

  • 写回答

1条回答 默认 最新

  • douchuo0730 2010-07-13 16:03
    关注

    Use php to create the array you want then. Maybe something like:

    $result = mysql_query($sql) or die(mysql_error());
    $newArray = array();
    while($row = mysql_fetch_assoc($result)){
        $newArray[$row['name']][$row['category_title']][] = $row['category_value'];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示