donqo88682 2015-08-09 03:15
浏览 246

如何从MySQL数据库中获取数据到一个字段作为数组索引的数组

I have a table named as demo with fields id, department, createddate and status.

Now i want to fetch all the data from this table to an array with index of array as department and values from each row with same department in that array for example:

Array[department]((Array[0]=>id
                            createddate 
                            status)
                  (Array[1]=>id
                            createddate 
                            status))

Can any one help me please?

  • 写回答

1条回答 默认 最新

  • dotxxh0998 2015-08-09 05:18
    关注

    You can use the following approach if you can afford to perform a loop on fetched rows and create a new array to meet your required index structure

    Once you fetch the db results, perform a loop on the results and push rows into a new array with index as department (I'm assuming its a unique property, and you should even think about renaming it to department_id).

    So you easily can do something like this:

    <?php
    
    $result = mysql_query('SELECT id, department, createddate, status FROM demo');
    $new_array = array();
    
    while($row = mysql_fetch_assoc($result)) {
        $department = $row['department'];
    
        // To add enter result row including deparment
        $new_array[$department] = $row; 
    
        // OR to have only id, createdate, status
        $new_array[$department] = 
                 array('id' => $row['id'], 
                       'createdate' => $row['createdate'],
                       'status' => $row['status']);
    
    }
    

    Note: To have department (department_id) as the index, it must be a unique property.

    评论

报告相同问题?

悬赏问题

  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别