duanbishai5271 2017-12-28 18:25
浏览 112
已采纳

使用两个循环遍历mysql表

I have following table in MySQL

|Column1|Column2|Column3|
-------------------------
|Data1  |Data2  |Data3  |
|Data4  |Data5  |Data6  |
|Data7  |Data8  |Data9  |
|Data10 |Data11 |Data12 |
-------------------------

Now in this table, I am fetching column names as well all the 12 cells using PHP

here is the loop that I am working on.

    for($i=0, $j=0; $i<$loopMax; $i++,$j++){//i run rows, j run columns
    if($j>=$column_count){
             $j=0;
    }
    $columns[$i][$j] = mysql_result($query_exec, $j, 'COLUMN_NAME');
    $response[$i][$columns[$i][$j]] = @$result[$j];
    }
     print_r($response);

$maxLoop is the value of a number of columns multiplied by the number of rows. that way I get the total number of cells I need to fetch. I have to send this response in a json string so getting this cell values along with its respective column names is important because that's what is going to help the UI end recognize where to put which value. there is no primary key to the table.

What I want to do is, fetch each of this cell value and the column name it belongs to and put it in an array. And send that array as jason string.

  • 写回答

2条回答 默认 最新

  • doukang7486 2017-12-28 20:19
    关注

    In case you have MySQL version 5.7.8 and above installed on your server, then you could use native JSON functions in your query.

    SELECT JSON_OBJECT('Column1', `Column1`, 'Column2', `Column2`, 'Column3', `Column3`);
    

    The result would be something like...

    { "Column1":"Data1", "Column2":"Data2", "Column3":"Data3" },
    ...
    ...
    { "Column1":"Data10", "Column2":"Data11", "Column3":"Data12" }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示